[英]How can I set up a specific timezone for angular material datepicker?
我正在Angular 7中开发应用程序。在日期字段中,我使用了角材料datepicker inout。 问题是,选择日期后,日期选择器始终采用用户本地时区。 但我想将其设置为特定的时区,例如东部或太平洋时区。 当用户选择一个日期时,它应该总是到那个特定的时区。 太平洋06/22/2019 23:59 我是新手。 如何在Angular 7应用程序中做到这一点? 先感谢您。
从Angular Material文档中 ,提供的DateAdapter的默认值是使用用户的时区。
您必须提供自己的DateAdapter才能覆盖它。
我找到了这个StackBlitz示例 , 该示例显示了解决此问题的可能方法,但还没有尝试过。
这是一个摘录:
@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);
}
}
用户日期格式
// 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.