Angular 材质日期选择器没有任何我们可以直接应用日期格式的方法或属性,但在 @angular/material 库的帮助下,您可以自定义格式化服务。
HTML:
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="select date" (dateChange)="onChange($event.value)">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp startView="month"></mat-datepicker>
</mat-form-field>
第一步:导入所需的类和常量变量。
import { NativeDateAdapter, MAT_DATE_FORMATS, DateAdapter } from "@angular/material";
Step2:使用NativeDateAdapter类方法进行格式化。
const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
return `${months[month]} ${year}`;
}
return date.toDateString();
}
}
第三步:声明日期格式常量。
export const APP_DATE_FORMATS =
{
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'numeric' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
第四步:在组件或主模块下注册提供者
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
providers: [
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
})
export class TestComponent {
constructor() { }
onChange(val) {
var d = new Date(val);
let date = [d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('01').slice(-2)].join('-');
console.log(date);
}
}
选择:2018 年 2 月 14 日
展示:2018 年 2 月
输出:2018-02-01(在.ts文件中)