gpt4 book ai didi

angular - Angular Material 日期选择器中的日期不正确

转载 作者:太空狗 更新时间:2023-10-29 16:58:19 26 4
gpt4 key购买 nike

当我选择一个日期时,我会在字段中看到正确的日期,但是当我保存时,日期选择器会在我选择的日期前一天发送(偏移 3 小时)我正在为日期选择器使用 Angular react 形式和 MatMomentDateModule。

问题与时区有关,但我只想保存用户输入数据库的相同日期。

此处转载的代码:https://stackblitz.com/edit/angular-material-moment-adapter-example-kdk9nk?file=app%2Fapp.module.ts

issue on stackblitz

githup 上与此相关的问题:

https://github.com/angular/material2/issues/7167

感谢任何帮助,我认为很多开发人员都需要解决方案。

最佳答案

两天前,在 https://github.com/angular/material2/issues/7167 ,Silthus 发布了他的解决方法,该方法覆盖了 MomentJsD​​ataAdapter。我试过了,它在全局任何地方都起到了魅力的作用。

首先他添加了一个扩展 MomentDateAdapter 的 MomentUtcDateAdapter

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 },
...
],

关于angular - Angular Material 日期选择器中的日期不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com