问题描述
在输入字段中填充日期(而不是通过日期选择器本身)时,日期将被视为美国格式.例如,在输入字段-10/01/2019中输入后,它将变为01/10/2019,当打开日期选择器时,日期将是2019年10月的第一天.
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.
通过日期选择器选择日期时,没有问题,所选日期显示为dd/MM/yyyy
when selecting the date via the date picker there is no issue and selected date is displayed as dd/MM/yyyy
推荐答案
UPDATE 格式函数中存在错误",需要在('0'+(date.getMonth()+ 1)).slice(-2)-
UPDATEThere was a "bug" in format function -need a parenthesis in ('0'+(date.getMonth()+1)).slice(-2)-
只需创建一个DateAdapter
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()
}
}
然后用作提供者
@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()));
}
参见
这篇关于Angular Material日期选择器输入将日期视为美国格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!