【发布时间】:2019-07-12 00:15:06
【问题描述】:
我正在 Angular 7 中开发一个应用程序。有一个日期字段,我在其中使用角度材料 datepicker inout。问题是,选择日期时,日期选择器总是采用用户本地时区。 但我想将其设置为特定时区,例如东部或太平洋时区。当用户选择一个日期时,它应该总是到达那个特定的时区。太平洋时间 2019 年 6 月 22 日 23:59。 我是角度的新手。如何在 Angular 7 应用程序中做到这一点?提前谢谢你。
【问题讨论】:
我正在 Angular 7 中开发一个应用程序。有一个日期字段,我在其中使用角度材料 datepicker inout。问题是,选择日期时,日期选择器总是采用用户本地时区。 但我想将其设置为特定时区,例如东部或太平洋时区。当用户选择一个日期时,它应该总是到达那个特定的时区。太平洋时间 2019 年 6 月 22 日 23:59。 我是角度的新手。如何在 Angular 7 应用程序中做到这一点?提前谢谢你。
【问题讨论】:
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 }
【讨论】:
您需要满足以下条件:
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);
}
}
【讨论】: