angular将不同的系统时区转换为北京时间
今天某个客户跟我们的产品经理反馈,咱们的管理后台同一条数据在不同电脑的时间显示竟然不同,差了八个小时。此时我便立即意识到是这位客户的电脑时区设置有问题。不禁为我这个月的奖金担忧起来,虽然是客户的电脑问题,但毕竟问题是出在我们的系统,我们也不能要求客户去修改电脑的时区。就像我们人生的哲学道路上应该遵从的一条道理:我们无法改变环境,那只有改变自身去融入这个环境。
首先查看文档
可以看出,管道提供了一个参数来设置显示某个时区的时间
于是最简单的解决方式是:
{{timestamp | date:‘yyyy-MM-dd HH:mm:ss’:‘GMT+08:00’}}
GMT+08:00是什么呢?
意思是设置当前时区为东八区
或者使用自定义pipe
// core/pipe/china-date.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'chinaDate'
})
export class ChinaDatePipe extends DatePipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
let format = 'yyyy-MM-dd HH:mm:ss';
if (args.length > 0) {
if (args[0] === 'date') {
format = 'yyyy-MM-dd';
} else if (args[0] === 'datetime') {
format = 'yyyy-MM-dd HH:mm:ss';
} else {
format = args[0];
}
}
return super.transform(value, format, 'UTC+8');
}
}
在app.module.ts中引入后
{{timestamp | chinaDate:‘yyyy-MM-dd HH:mm:ss’}}
其原理都是将时区设置为东八区
好啦,这个月的奖金还有得补救了,哈哈~