我正在尝试为material2中闪亮的新datepicker实现我自己的日期格式。根据文档,我必须提供我的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'},
}
};我得到一个错误,日期输入为空。但是它到底是什么类型的呢?文档上说什么都行。
如果我试图把一些伪函数放在那里,我会得到错误:_dateAdapter.parse is not a function.
function dateInput() {
return 'ddd';
}
const MY_DATE_FORMATS: MdDateFormats = Object.assign({}, MD_NATIVE_DATE_FORMATS, {parse: dateInput });如何让它工作?
发布于 2017-06-12 23:03:07
非常感谢@MariusR,他推动了这个解决方案。如上所述,您需要提供自己的日期适配器。从plunkr看,这很简单:
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文件,只需要在组件的模块中提供日期选择器:
providers: [
{provide: DateAdapter, useClass: OurDateAdapter}
]在您的组件中,您需要在构造函数中使用它:
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('en-GB');
}区域设置的列表可以在这里收集,plunkr示例使用葡萄牙语,我的是英国英语。
http://www.i18nguy.com/unicode/language-identifiers.html
MariusR,行个礼吧,为什么官方文件不能有这个?
发布于 2017-05-29 19:54:04
在您的代码中,应该将
{provide: DateAdapter, useValue: NativeDateAdapter },使用
{provide: DateAdapter, useClass: NativeDateAdapter },因为NativeDateAdapter是一个类,而不是常量。
这应该会解决你的.parse不是一个函数错误的问题。
我无法复制日期输入为空的错误。可能是由于相同的useClass问题造成的,但是如果仍然遇到错误,您可以将dateInput定义为
parse: {
dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
},或者是
parse: {
dateInput: 'YYYY-MM-DD',
},发布于 2017-07-11 23:28:20
Angular实现默认使用Javascript date实现,这意味着您可能希望创建自己的MdDateFormats和DateAdapter实现,以便获得日期的自定义表示形式。正如@MariusR所说:
在代码中,您应该将
{provide: DateAdapter, useValue: NativeDateAdapter },带
{provide: DateAdapter, useClass: NativeDateAdapter },
我制作了一个project,展示了如何实现自定义的MdDateFormats和DateAdapter (实现日期以适应“es-UY”区域设置)。它使用Moment.js来表示其他日期格式,并且它的实现可以完全定制以满足您的需求。自定义区域设置文件为here。
https://stackoverflow.com/questions/44201050
复制相似问题