Iñi*_*igo 7 typescript angular-material mat-datepicker
使用日期选择器选择日期时,一切正常,以所需格式显示日期: DD/MM/YYYY
但是当手动输入带有 format 的日期时DD/MM/YYYY
,datepicker 会自动将日期更改为MM/DD/YYYY
,将第一个值检测DD
为月份。
如何使手动输入被检测为DD/MM/YYYY
,而不是MM/DD/YYYY
?
谢谢!
<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>
Run Code Online (Sandbox Code Playgroud)
您需要像这样构建一个自定义日期适配器:
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, '');
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的应用中使用它:
@NgModule({
....
providers: [
{ provide: DateAdapter, useClass: CustomDateAdapter }
]
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6245 次 |
最近记录: |