我需要帮助。我不知道如何更改 Material 2 日期选择器的日期格式。我已经阅读了文档,但我不明白我实际需要做什么。 datepicker默认提供的输出日期格式f.e.: 6/9/2017
我想要实现的是将格式更改为 9-Jun-2017 或任何其他格式。
文档 https://material.angular.io/components/component/datepicker根本帮不了我。 提前致谢
最佳答案
这是我找到的唯一解决方案:
首先,创建常量:
const MY_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
// dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
然后你必须扩展 NativeDateADapter:
export class MyDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
在格式功能中,你可以选择你想要的任何格式
最后一步,您必须将其添加到模块提供程序中:
providers: [
{provide: DateAdapter, useClass: MyDateAdapter},
{provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],
就是这样。我不敢相信没有什么简单的方法可以通过@Input 更改日期格式,但我们希望它会在 Material 2 的某个 future 版本(目前是 beta 6)中实现。
关于javascript - Angular 2 Material 2日期选择器日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452966/