Angular Material date picker input treat the date

2019-07-11 02:03发布

问题:

When populating the date in the input field (not via the datepicker itself) date is treated as US format. For example, after typing in input field - 10/01/2019 it becomes 01/10/2019 and when opening the date picker the date is first of October 2019.

when selecting the date via the date picker there is no issue and selected date is displayed as dd/MM/yyyy

回答1:

UPDATE There was a "bug" in format function -need a parenthesis in ('0'+(date.getMonth()+1)).slice(-2)-

just create a DateAdapter

import {NativeDateAdapter,DateAdapter} from '@angular/material';

export class MyDateAdapter extends NativeDateAdapter{
  parse(value: string) {
    let it=value.split('/');
    if (it.length==3)
    return new Date(+it[2],+it[1]-1,+it[0],12)
  }

  format(date: Date, displayFormat: Object) {
    return ('0'+date.getDate()).slice(-2)+'/'+
           ('0'+(date.getMonth()+1)).slice(-2)+'/'+date.getFullYear()
  }
}

Then use as provider

@Component({
  selector: 'datepicker-formats-example',
  templateUrl: 'datepicker-formats-example.html',
  styleUrls: ['datepicker-formats-example.css'],
    providers: [
    {provide: DateAdapter, useClass: MyDateAdapter}
  ],

})
export class DatepickerFormatsExample {
  date = new FormControl(new Date(Date.now()));
}

see in

stackblitz



回答2:

If you are using the angular material datepicker you can overide the locale wich is US by default. see this link : https://material.angular.io/components/datepicker/overview#internationalization

You need to set the useValue to fr-FR or other locale that uses the dd/MM/yyyy

@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'fr-FR'},
  ],
})
export class MyApp {}