【问题标题】:How can I set up a specific timezone for angular material datepicker?如何为角度材料日期选择器设置特定时区?
【发布时间】:2019-07-12 00:15:06
【问题描述】:

我正在 Angular 7 中开发一个应用程序。有一个日期字段,我在其中使用角度材料 datepicker inout。问题是,选择日期时,日期选择器总是采用用户本地时区。 但我想将其设置为特定时区,例如东部或太平洋时区。当用户选择一个日期时,它应该总是到达那个特定的时区。太平洋时间 2019 年 6 月 22 日 23:59。 我是角度的新手。如何在 Angular 7 应用程序中做到这一点?提前谢谢你。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    From the Angular Material docs,提供的 DateAdapter 默认使用用户的时区。

    您必须提供自己的 DateAdapter 来覆盖它。

    我发现this StackBlitz example 显示了解决此问题的可能方法,但还没有尝试过。

    这里有一个 sn-p:

    @Injectable()
    export class CustomDateAdapter extends MomentDateAdapter {
    
      constructor( @Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
        super(dateLocale);
      }
    
      parse(value, parseFormat) {
        if (value && typeof value == 'string') {
          console.log(moment(value, parseFormat, this.locale, true));
          return moment(value, parseFormat, this.locale, true);
        }
        return value ? moment(value).locale(this.locale) : undefined;
      }
    }
    

    并提供它(简单版):

    { provide: DateAdapter, useClass: CustomDateAdapter }
    

    【讨论】:

      【解决方案2】:

      您需要满足以下条件:

      1. 创建用户日期格式管道。
      2. 创建一个扩展 NativeDateAdapter 的自定义日期适配器。
      3. CustomDateAdapter 导入到一个模块中,该模块将用作useClass: CustomDateAdapter

      app.module.ts

      @NgModule({
        imports: [],
        declarations: [],
        exports: [],
        entryComponents: [],
        providers: [{
          provide: DateAdapter,
          useClass: CustomDateAdapter
        }]
      })
      export class AppModule {}
      

      custom-date-adaptor.ts

      export class CustomDateAdapter extends NativeDateAdapter {
        format(date: Date): string {
          const pipe = new UserDateFormatPipe();
          return pipe.transform(date);
        }
      }
      

      user-date-format.ts

      // using moment.js
      export class UserDateFormatPipe implements PipeTransform {
      
        transform(date: string | Date, timeFormat: string = ''): string {
          const defaultValues = {
            dateFormat: 'MM-dd-yyyy',
            language: 'en-US',
            timeZone: 'Central' //change defaults accordingly
          };
          const timeZoneOffset = moment(new Date(date))
            .tz(defaultValues)
            .format('Z');
          const datePipe = new DatePipe(defaultValues.language);
          const dateFormat = timeFormat ? `${defaultValues.dateFormat}  ${timeFormat}` : defaultValues.dateFormat;
          return datePipe.transform(date, dateFormat, timeZoneOffset, defaultValues.language);
        }
      }
      

      Stackblitz-Demo

      【讨论】:

      • 感谢您的回答。您能否提供使用此代码的示例 angular 7 项目?我对在 Angular 7 中使用 moment.js 感到有点困惑。
      猜你喜欢
      • 1970-01-01
      • 2016-12-06
      • 2018-09-13
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多