如何以MM / DD / YYYY格式自定义mat-datepicker日期?
我使用以下配置:
HTML:
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
TS:
import {Component} from '@angular/core';
/** @title Basic datepicker */
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {}
当我打印表单值时,它会给出以下输出:
Sun Dec 31 2017 00:00:00 GMT + 0530(IST)
我期待MM / DD / YYYY格式。
我尝试了这种配置:https://material.angular.io/components/datepicker/overview#customizing-the-parse-and-display-formats
但它对我没用。我使用默认的MatNativeDateModule(非时刻js)
答案 0 :(得分:6)
您可以按如下方式使用日期管道
<input mdInput placeholder="Title" [ngModel]="mydate | date:'MM-dd-yyyy'">
<强> DEMO
强>
答案 1 :(得分:6)
以下代码将格式化您的角度应用程序中所有日期选择器的日期。
为日期格式创建一个常量。
export const DateFormat = {
parse: {
dateInput: 'input',
},
display: {
dateInput: 'MM/DD/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'MM/DD/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
}
};
然后在应用模块中使用以下代码
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: DateFormat }
]