我正在将日期自定义为 dd-mmm-yyy,例如 2019 年 2 月 12 日,使用角度 Material 6,这是我的代码,我尚未使用替换功能,但尚未收到此错误
组件文件内容
import { MomentDateAdapter ,MatMomentDateModule } from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';
import {default as _rollupMoment, Moment} from 'moment';
import * as _moment from 'moment';
export class MyDateAdapter extends NativeDateAdapter {
// constructor() {
// super('en-US');
// }
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);
}
}
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
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'},
}
};
以及 HTML 部分
<div class="col-lg-4 m-form__group-sub">
<mat-form-field class="example-full-width" appearance="outline">
<mat-label>Invoice Date</mat-label>
<input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker1" placeholder="Choose a date" formControlName="inv_date">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</div>
最佳答案
要具有 UTC Material 日期选择器行为和特定日期格式:
- 安装
@angular/material-moment-adapter
并确保moment
lib也已安装。 - 导入
MatMomentDateModule
。 - 将
{ Provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true }}
添加到模块的提供程序数组中。 - 可选。要覆盖日期选择器中的显示值,请使用以下命令设置区域设置:
{ Provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
以便 Material 日期选择器具有全局 dd/M/yyyy 视觉格式<
从现在开始, Material 日期选择器将与 UTC 配合使用。日期选择器的输出也将是 UTC,无需调整时区。
对于非常高级的情况,请使用自定义 DateAdapter 实现和 DateFormats 而不是上述所有内容。 {提供:DateAdapter,useClass:MyDateAdapter},
{提供:MAT_DATE_FORMATS,useValue:MY_DATE_FORMATS}
有关更多信息,请查看 material API docs
关于angular6 - Angular Material 自定义日期选择器格式引发错误 "format.replace is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54867168/