我需要帮助。我不知道如何改变资料2的日期格式。我读过文档,但我不明白我到底需要做什么。默认情况下,datepicker提供的输出日期格式为f.e.:6/9/2017
我想要实现的是将格式改为2017年6月9日或其他任何形式。
文档https://material.angular.io/components/component/datepicker根本帮不了我。提前感谢
发布于 2017-06-15 11:27:16
这里是我为这个问题找到的唯一解决方案:
首先,创建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:
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来更改日期格式,但我们希望它能在将来的材料2版本(目前是beta 6)中实现。
发布于 2017-07-13 12:52:49
伊戈尔的回答对我没有用,所以我直接在角2材料的github上问,有人给了我这个答案,这个答案对我有用:
${day}-${month}-${year};}返回date.toDateString();}}更多信息这里
编辑:对于那些遇到手动输入问题的人,格式不受尊重,您可以从NativeDateAdapter重写parse(value: any)函数,如下所示。
parse(value: any): Date | null {
const date = moment(value, 'DD/MM/YYYY');
return date.isValid() ? date.toDate() : null;
}因此,自定义适配器将采取以下最后形式。
import { NativeDateAdapter } from "@angular/material";
import * as moment from 'moment';
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${day}/${month}/${year}`;
}
return date.toDateString();
}
parse(value: any): Date | null {
const date = moment(value, environment.APP_DATE_FORMAT);
return date.isValid() ? date.toDate() : null;
}
}发布于 2018-03-30 07:06:07
您只需要提供一个自定义的MAT_DATE_FORMATS
export const APP_DATE_FORMATS = {
parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}},
display: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'},
monthYearLabel: {year: 'numeric'}
}
};并将其添加到提供者。
providers: [{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}]工作代码
https://stackoverflow.com/questions/44452966
复制相似问题