当我选择一个日期时,我在字段中看到了正确的日期,但是,当我保存时,数据报警器会在我选择的日期(3小时偏移)的前一天发送,我正在使用角反应形式和MatMomentDateModule作为数据选择器。
问题与时区有关,但我只想保存用户输入数据库的相同日期。
这里介绍的代码:https://stackblitz.com/edit/angular-material-moment-adapter-example-kdk9nk?file=app%2Fapp.module.ts
在githup上与此相关的问题:
https://github.com/angular/material2/issues/7167
任何帮助都是值得赞赏的,我认为很多开发人员都需要一个解决方案。
发布于 2018-05-02 10:17:47
两天前,在https://github.com/angular/material2/issues/7167,西尔瓦发布了他的解决方案,凌驾于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 },
...
],
发布于 2019-07-15 01:13:16
只需将选项useUtc: true
用于MatMomentDateAdapter
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
@NgModule({
exports: [
MatMomentDateModule,
// ...
],
providers: [
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
],
})
export class CustomModule { }
发布于 2018-09-15 14:17:34
https://github.com/angular/material2/issues/7167#issuecomment-402061126
通过提供MAT_MOMENT_DATA_ADAPTER_OPTIONS并将其设置为useUtc: true,您可以更改默认行为以将日期解析为UTC。
@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]
})
https://stackoverflow.com/questions/48710053
复制相似问题