Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material date picker input treat the date as US format

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

like image 445
Shauly Yonay Avatar asked Oct 26 '25 15:10

Shauly Yonay


1 Answers

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

like image 176
Eliseo Avatar answered Oct 28 '25 06:10

Eliseo



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!