Kay*_*Kay 9 angular-material angular
我将日期的语言环境设置为 en-GB - 这样日期选择器就可以采用英国格式。
如果我手动输入日期10/12/2018(2018 年 12 月 10 日)并点击选项卡,日期将转换为12/10/2018(12th October 2018) 。
使用选择器选择原始日期工作正常,此问题仅在手动输入和指定区域设置时发生。
https://stackblitz.com/edit/angular-hv6jny
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
——
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
]
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({
....
provide: DateAdapter, useClass: CustomDateAdapter }
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3282 次 |
| 最近记录: |