Angular - How to exclude timezone hours from formatted date in a date pipe?
我正在尝试格式化日期,但每次遇到格式化时,都会遇到将时区添加到时间的问题。调用
我正在使用
由于格林尼治标准时间(GMT)为2,我该如何格式化日期并避免在日期中增加额外的小时数?对于
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Pipe({ name: 'exactDate' }) export class ExactDatePipe implements PipeTransform { transform(value: string, args: string) { const parsedDate: string = datefns.format(new Date(value).toUTCString(), args); return parsedDate; } } |
date-fns非常清楚,
It always returns a date in the local timezone, no matter what you passed: a timestamp, a string or a date object.
如果我正确理解了您的问题,则您不希望出现这种情况。而是尝试使用Date.toLocaleString函数提供的options参数,例如
1 2 3 4 5 6 7 | var date = new Date(), options = { timeZone: 'UTC', timeZoneName: 'short' }, str = date.toLocaleString('en-US', options); // str format like"5/31/2017, 1:55:21 PM GMT" |
您完全可以控制格式-这是MDN文档。