当我选择一个日期时,我在字段中看到了正确的日期,但是,当我保存时,日期选择器发送我选择的日期前一天(3小时偏移)
我使用角度反应形式和MatMomentDateModule作为日期选择器.
我使用角度反应形式和MatMomentDateModule作为日期选择器.
代码在这里重新编写:https://stackblitz.com/edit/angular-material-moment-adapter-example-kdk9nk?file=app%2Fapp.module.ts
与githup相关的问题:
https://github.com/angular/material2/issues/7167
任何帮助表示赞赏,我认为很多开发人员需要一个解决方案.
两天前,在
https://github.com/angular/material2/issues/7167,Silthus发布了他的解决方法,覆盖了MomentJsDataAdapter.我尝试过它,它可以作为全球任何地方的魅力.
首先,他添加了MomentUtcDateAdapter,扩展了MomentDateAdapter
import { Inject,Injectable,Optional } from '@angular/core'; import { MAT_DATE_LOCALE } from '@angular/material'; import { MomentDateAdapter } from '@angular/material-moment-adapter'; import { Moment } from 'moment'; import * as moment from 'moment'; @Injectable() export class MomentUtcDateAdapter extends MomentDateAdapter { constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) { super(dateLocale); } createDate(year: number,month: number,date: number): Moment { // Moment.js will create an invalid date if any of the components are out of bounds,but we // explicitly check each case so we can throw more descriptive errors. if (month < 0 || month > 11) { throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } if (date < 1) { throw Error(`Invalid date "${date}". Date has to be greater than 0.`); } let result = moment.utc({ year,month,date }).locale(this.locale); // If the result isn't valid,the date must have been out of bounds for this month. if (!result.isValid()) { throw Error(`Invalid date "${date}" for month with index "${month}".`); } return result; } }
然后在AppModule组件中,您必须这样做:
providers: [ ... { provide: MAT_DATE_LOCALE,useValue: 'en-GB' },{ provide: MAT_DATE_FORMATS,useValue: MAT_MOMENT_DATE_FORMATS },{ provide: DateAdapter,useClass: MomentUtcDateAdapter },... ],