Angular 2 Material 2 datepicker日期格式 [英] Angular 2 Material 2 datepicker date format
问题描述
我需要帮助。我不知道如何更改材料2 datepicker的日期格式。我已阅读文档,但我不明白我实际需要做什么。 datepicker默认提供的输出日期格式为fe:6/9/2017
I need help. I don't know how to change the date format of the material 2 datepicker. I've read documentation but I don't understand what I actually need to do. Output date format which datepicker provides by default is f.e.: 6/9/2017
我想要实现的是将格式更改为2017年6月9日或任何其他。
What I'm trying to achieve is to change format to the 9-Jun-2017 or any other.
文档 https://material.angular .io / components / component / datepicker 根本没有帮助我。
提前致谢
Documentation https://material.angular.io/components/component/datepicker doesn't help me at all. Thanks in advance
推荐答案
以下是我找到的唯一解决方案:
Here is the only solution I found for this one:
首先,创建const:
First, create const:
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:
Then you have to extend 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);
}
}
在格式化功能中,您可以选择任何您想要的格式
最后一步,您必须将其添加到模块提供商中:
And the last step, you have to add it into module providers:
providers: [
{provide: DateAdapter, useClass: MyDateAdapter},
{provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],
就是这样。我无法相信没有一些简单的方法可以通过@Input更改日期格式,但我们希望它将在未来版本的材料2(目前 beta 6 )中实现。
And that's it. I can not believe that there is no some easy way to change date format through the @Input but let's hope it will be implemented in some future version of material 2 (currently beta 6).
这篇关于Angular 2 Material 2 datepicker日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!