Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Angular Material date-picker inside Formly form for service layer (not display format)

I would like to expose my date value as date only ("yyyy-MM-dd") on an Angular Material date picker. Currently, the default date value is an ISO format (includes time).

I have a starter Stackblitz project with the the required setup. The formly-datepicker.type is where I would like to centralize the conversion so that any date used in the model will be formatted properly for the service layer.

One of my attempts to accomplish it in a centralized manner is using the Angular ControlValueAccessor, but the value is never updated. ControlValueAccessor Stackblitz

In the example Stackblitz, after changing the date and clicking Submit the value I need returned would be something like: {"mydate":"1940-03-11"}(without the time information).

like image 869
Gone Avatar asked Oct 26 '25 00:10

Gone


1 Answers

So , I think I have solution for you to display mat datepicker as ("yyyy-MM-dd") format. To do that Install to dependencies "@angular/material-moment-adapter": "^11.1.2" and "moment": "^2.18.1" (both are current version). Then import in your formly-datepicker-type.component.ts file these 2 libraries.

import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

Then add a date format like below in your formly-datepicker-type.component.ts file.=>

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'YYYY-MM-DD',
    monthYearLabel: 'YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'YYYY',
  },
};

After that Update @Component by adding providers like below =>

@Component({
  selector: "app-formly-datepicker-type",
  templateUrl: "./formly-datepicker-type.component.html",
  styleUrls: ["./formly-datepicker-type.component.css"],
   providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ]
}) 

Finally, Date time will show as wanted.
Note: I have updated you sample code of stackblitz. Please check my demo link =>Stackblitz mat-datepicker Date-Time Format.

like image 195
Srijon Chakraborty Avatar answered Oct 28 '25 17:10

Srijon Chakraborty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!