Use utc+0 with MAT_DATE_LOCALE in Angular Material 8

4.6k views Asked by At

I'm using Angular 8 and Angular Material 8. My application has this code in AppModule:

{ provide: MAT_DATE_LOCALE, useFactory: "myFunctionToGetServerLanguageCode" }

Where myFunctionToGetServerLanguageCode is a method that returns a string like "en-US" (based on server). Then, I have this component with a datepicker from Angular Material with these specific providers:

    providers: [
    { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
    { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
    { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
],

In this way I intended:

  • to use moment with the datePicker;
  • to make the datepicker use utc+0;
  • to use the same format as the culture;

For example with a MAT_DATE_LOCALE with "en-US": If I pick 10th April 2020, I expected that the picker shows "04/10/2020" (e.g. with a "L" format that will be set as MM/DD/YYYY) and emits "2020-04-10T00:00:00.000Z"

What happens is that the picker emits "2020-04-09T23:00:00.000Z". Using the developers tools, the value emitted is a Moment with the private property "_isUtc" set as false.

Where am I wrong?

1

There are 1 answers

1
E.Tiake On BEST ANSWER

I found the problem: I replaced these:

 providers: [
 { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
 { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
 { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }]

with:

providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, 
  MAT_MOMENT_DATE_ADAPTER_OPTIONS] },
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }, 
{
    provide: MAT_DATE_FORMATS, useValue: {
        parse: {
            dateInput: "L",
        },
        display: {
            dateInput: "L",
            monthYearLabel: "MMM YYYY",
            dateA11yLabel: "LL",
            monthYearA11yLabel: "MMMM YYYY",
        },
    }
}]

Yeah! I hope this can help someone else!