gpt4 book ai didi

angular - 如何从 Angular 2 设置 DatePicker 的时区?

转载 作者:行者123 更新时间:2023-12-02 17:37:55 32 4
gpt4 key购买 nike

有没有办法在 Angular Material 2 的日期选择器上设置时区?

组件:

  <mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>

最佳答案

要在日期选择器上设置时区,您需要创建一个自定义 DateAdapter,如 @lee-richardson 提到的。

以下实现适用于 Angular 11.0.0。

https://stackblitz.com/edit/angular-zbmhw5-n955ki

我如何创建这个 stackblitz:

  • 我 fork 了 Angular Material documentation illustrating the basic datepicker 提供的 stackblitz

  • 我安装了时刻时区依赖项

  • 我创建了一个 custom-moment-date-adapter.ts 并继承自 MomentDateAdapter由 Angular/Component 提供。然后我重写了 createDatedeserializeparsetoday 方法。

  • 例如,我对时区进行了硬编码,但您可以调整代码以从您喜欢的位置获取时区。

    import { Inject, Injectable, Optional } from "@angular/core";
    import { MomentDateAdapter } from "@angular/material-moment-adapter";
    import { MAT_DATE_LOCALE } from "@angular/material/core";
    import moment from "moment-timezone";

    @Injectable()
    export class CustomMomentDateAdapter extends MomentDateAdapter {
    constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
    super(dateLocale);
    }

    static TIMEZONE = "Asia/Sakhalin";

    createDate(year: number, month: number, date: number): moment.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.`);
    }

    const monthString = ("0" + (month + 1)).slice(-2);
    const yearSting = ("0" + date).slice(-2);
    const dateString = `${year}-${monthString}-${yearSting} 00:00`;
    const result = moment.tz(dateString, CustomMomentDateAdapter.TIMEZONE);

    // 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;
    }

    /**
    * Returns the given value if given a valid Moment or null. Deserializes valid ISO 8601 strings
    * (https://www.ietf.org/rfc/rfc3339.txt) and valid Date objects into valid Moments and empty
    * string into null. Returns an invalid date for all other values.
    */
    deserialize(value: any): moment.Moment | null {
    let date;
    if (value instanceof Date) {
    date = this._createMoment2(value).locale(this.locale);
    } else if (this.isDateInstance(value)) {
    // Note: assumes that cloning also sets the correct locale.
    return this.clone(value);
    }
    if (typeof value === "string") {
    if (!value) {
    return null;
    }
    date = this._createMoment2(value, moment.ISO_8601).locale(this.locale);
    }
    if (date && this.isValid(date)) {
    return this._createMoment2(date).locale(this.locale);
    }
    return super.deserialize(value);
    }

    parse(value: any, parseFormat: string | string[]): moment.Moment | null {
    if (value && typeof value === "string") {
    return this._createMoment2(value, parseFormat, this.locale);
    }
    return value ? this._createMoment2(value).locale(this.locale) : null;
    }

    today(): moment.Moment {
    return moment()
    .utc()
    .tz(CustomMomentDateAdapter.TIMEZONE)
    .local(this.locale);
    }

    /** Creates a Moment instance while respecting the current UTC settings. */
    private _createMoment2(
    date: moment.MomentInput,
    format?: moment.MomentFormatSpecification,
    locale?: string
    ): moment.Moment {
    const date2 = moment(date, format, locale).format("YYYY-MM-DD");
    return moment.tz(date2, CustomMomentDateAdapter.TIMEZONE);
    }
    }
  • 在模块中(我的 stackblitz 示例中的 DemoMaterialModule):2.1)我导入了MatMomentDateModule2.2)我注入(inject)了新创建的CustomMomentDateAdapter
  • providers: [{ provide: DateAdapter, useClass: CustomMomentDateAdapter }]
  • 为了本示例的目的,我更新了 datepicker-overview-example 组件。
  • 我用来找到此解决方案的其他引用文献:

    关于angular - 如何从 Angular 2 设置 DatePicker 的时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936422/

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