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>
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With