0

I have this input for selectin date

<mat-form-field class="w-full">
                                <mat-label>{{ "DATE" | translate }}</mat-label>
                                <input matInput [matDatepicker]="datePicker" [formControlName]="'date'" />
                                <mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
                                <mat-datepicker #datePicker></mat-datepicker>
                                <mat-error>
                                    {{ 'REQUIRED' | translate }}
                                </mat-error>
                            </mat-form-field>

I also have added this to my component


const MY_DATE_FORMAT = {
    parse: {
        dateInput: 'DD/MM/YYYY',
    },
    display: {
        dateInput: 'DD/MM/YYYY', 
        monthYearLabel: 'MMMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY'
    }
};

@Component({
    selector: 'app-document',
    templateUrl: './document.component.html',
    styleUrls: ['./document.component.scss'],
    encapsulation: ViewEncapsulation.None,
    providers: [
        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
        { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMAT },
      ],
})

When selecting the date from the input it shows it incorrectly(one day earlier then selected) p.s: I have selected 10/05/2024 Using console.log for before saving the data shows this "2024-05-09T22:00:00.000Z" It has selected 09 instead of 10!

Any reason why this is happening?

1 Answer 1

0

According to the Angular Material Datepicker documentation,

By default the MomentDateAdapter creates dates in your time zone specific locale. You can change the default behaviour to parse dates as UTC by passing useUtc: true into provideMomentDateAdapter or by providing the MAT_MOMENT_DATE_ADAPTER_OPTIONS injection token.

The date time selected is based on your local timezone. You need to inject the MAT_MOMENT_DATE_ADAPTER_OPTIONS token so that it use the UTC timezone.

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter } from '@angular/material-moment-adapter';
providers: [
  {
    provide: DateAdapter,
    useClass: MomentDateAdapter,
    deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
  },
  { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMAT },
  { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]

Demo @ StackBlitz

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.