如何实现日期选择器的MD_DATE_FORMATS? [英] How to implement MD_DATE_FORMATS for datepicker?
问题描述
我正在尝试为material2中的闪亮的新日期选择器实现自己的日期格式.根据文档,我必须提供我的MD_DATE_FORMATS版本:
I'm trying to implement my own date format for shiny new datepicker from material2. According to documentation i have to provide my version of MD_DATE_FORMATS:
providers: [
{provide: DateAdapter, useValue: NativeDateAdapter },
{provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS },
],
当我使用默认实现时:
export const MD_NATIVE_DATE_FORMATS: MdDateFormats = {
parse: {
dateInput: null,
},
display: {
dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
我收到一个错误,指出日期输入为空.但是它到底是什么类型?文档说明了什么.
I get an error that date input is null. But what type it really is? Documentation says any.
如果我尝试在其中放置一些虚拟函数,则会出现错误: _dateAdapter.parse不是函数.
If i try to put some dummy function there i get error: _dateAdapter.parse is not a function.
function dateInput() {
return 'ddd';
}
const MY_DATE_FORMATS: MdDateFormats = Object.assign({}, MD_NATIVE_DATE_FORMATS, {parse: dateInput });
如何使其工作?
推荐答案
非常感谢@MariusR提出了解决方案.如前所述,您需要提供自己的日期适配器.在plunkr中,这很简单,如下所示:
Many thanks to @MariusR who pushed the solution. As stated you need to provide your own date adapter. From the plunkr, this is as simple as follows:
export class OurDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
return new Date(Number(str[2]), Number(str[1])-1, Number(str[0]), 12);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
}
这可以是您的任何TS文件,只需在组件的模块中提供日期选择器即可:
This can be any of your TS files and just needs to be provided in the module of your component with the date picker:
providers: [
{provide: DateAdapter, useClass: OurDateAdapter}
]
在您的组件中,您需要在构造函数中使用它:
In your component you need to use it in the constructor:
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('en-GB');
}
可以在此处收集语言环境列表,plunkr示例使用葡萄牙语,我的语言是UK英语.
The list of locales can be gathered here, the plunkr example uses Portuguese, mine is UK English.
http://www.i18nguy.com/unicode/language-identifiers.html
MariusR,低头,为什么官方文档没有这个?
MariusR, take a bow, why can't the official docs have this?
这篇关于如何实现日期选择器的MD_DATE_FORMATS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!