Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Datepicker input format

When selecting a date with the datepicker, everything works great, displaying the date in the desired format: DD/MM/YYYY

But when entering manually a date with format DD/MM/YYYY, the datepicker automatically changes the date to MM/DD/YYYY, detecting the first value DD as a month.

How can I make the manual input be detected as DD/MM/YYYY, not as MM/DD/YYYY?

Thanks!

<mat-form-field class="datepickerformfield" floatLabel="never">
    <input matInput class="dp" formControlName="fpresentaciondesde" [matDatepicker]="picker5" placeholder="DD/MM/YYYY" required>
    <mat-datepicker-toggle matSuffix [for]="picker5"></mat-datepicker-toggle>
    <mat-datepicker #picker5></mat-datepicker>
</mat-form-field>
like image 339
Iñigo Avatar asked Sep 27 '19 10:09

Iñigo


People also ask

What is Mat datepicker toggle?

A datepicker is composed of a text input and a calendar pop-up, connected via the matDatepicker property on the text input. There is also an optional datepicker toggle button that gives the user an easy way to open the datepicker pop-up.


1 Answers

You need to build a custom date adapter like this:

export class CustomDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {

    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
       const str = value.split('/');

      const year = Number(str[2]);
      const month = Number(str[1]) - 1;
      const date = Number(str[0]);

      return new Date(year, month, date);
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }

  format(date: Date, displayFormat: Object): string {
    date = new Date(Date.UTC(
      date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(),
      date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
    displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' });

    const dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
    return dtf.format(date).replace(/[\u200e\u200f]/g, '');
  }

}

and then use it in your app:

@NgModule({
    ....
    providers: [
        { provide: DateAdapter, useClass: CustomDateAdapter }
    ]
})

DEMO

like image 99
Amadou Beye Avatar answered Sep 27 '22 21:09

Amadou Beye