[英]How can I set up a specific timezone for angular material datepicker?
I am developing an application in Angular 7. There is a date field where I use angular material datepicker inout. 我正在Angular 7中开发应用程序。在日期字段中,我使用了角材料datepicker inout。 The problem is, datepicker always takes user local timezone when a date is selected.
问题是,选择日期后,日期选择器始终采用用户本地时区。 But I want to set it up to a specific timezone such as Eastern or Pacific timezone.
但我想将其设置为特定的时区,例如东部或太平洋时区。 When user will select a date, it should always come to that specific timezone ex.
当用户选择一个日期时,它应该总是到那个特定的时区。 06/22/2019 23:59 Pacific.
太平洋06/22/2019 23:59 I am new to angular.
我是新手。 How can do it in Angular 7 application?
如何在Angular 7应用程序中做到这一点? Thank you in advance.
先感谢您。
From the Angular Material docs , the default for the provided DateAdapter is to use the user's time zone. 从Angular Material文档中 ,提供的DateAdapter的默认值是使用用户的时区。
You'll have to provide your own DateAdapter to override this. 您必须提供自己的DateAdapter才能覆盖它。
I found this StackBlitz example that shows a possible way to solve this, but have not tried it. 我找到了这个StackBlitz示例 , 该示例显示了解决此问题的可能方法,但还没有尝试过。
Here is a snippet from there: 这是一个摘录:
@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;
}
}
And providing it (simple version): 并提供它(简单版本):
{ provide: DateAdapter, useClass: CustomDateAdapter }
You'll need to the following: 您需要执行以下操作:
CustomDateAdapter
into a module where it'll be used as useClass: CustomDateAdapter
CustomDateAdapter
导入模块中,用作useClass: CustomDateAdapter
app.module.ts app.module.ts
@NgModule({
imports: [],
declarations: [],
exports: [],
entryComponents: [],
providers: [{
provide: DateAdapter,
useClass: CustomDateAdapter
}]
})
export class AppModule {}
custom-date-adaptor.ts 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.