如何使用Angular 4日期管道处理时区问题? [英] How can I deal with the timezone issue with the Angular 4 date pipe?
问题描述
我在每个对象中都有一个日期值,可以像这样打印:
I have a date value in each of my objects that I can Print like this:
<td> {{competition.compStart }}</td>
这是它的外观:
1931-05-31T00:00:00.000+0000
为了更改格式以使其更具可读性,我使用了Angular日期管道:
In order to change the format to make it more readable I'm using the Angular date pipe:
<td> {{competition.compStart | date : "dd/MM/yyyy"}}</td>
结果如下:
30/05/1931
如您所见,它显示的是前一天(5月30日而不是5月31日).
As you can see, It is displaying the previous day (May 30 instead of May 31).
据我了解,问题与时区有关,因为我在阿根廷,并且我们有GMT-3,那么第31天的00:00减去3小时将是5月30日晚上9点.
As far as I understand, the problem is related to the timezone, since I'm in Argentina and we have GMT-3 then 00:00 of the 31st minus 3 hours would be May 30 at 9 PM.
那么我如何才能使它真正地花费时间,而不是根据时区进行处理,而仍然在管道中应用该格式?
So how can I make it take the time literally and not process it based on the timezone, but still apply the format in the pipe?
推荐答案
在幕后,DatePipe
使用语言环境在用户的时区中显示日期.尝试使用客户的时区数据:
Behind the scenes, DatePipe
uses locale to display date in user's timezone. Try with client's timezone data:
1931-05-31T00:00:00.000-0300
而不是1931-05-31T00:00:00.000+0000
.
您可以使用(new Date()).getTimezoneOffset()
这实际上是DatePipe
的已知问题/局限性.社区意识到这一点.将来,您将可以将时区指定为参数({{ value | date:format:zone }}
)之一.
This is actually the known issue/limitation of DatePipe
. Community is aware of it. It the future, you will be able to specify timezone as one of parameters ({{ value | date:format:zone }}
).
这是github上的问题: https://github.com/angular/angular/issues/9324
Here is the issue on github: https://github.com/angular/angular/issues/9324
对于更高级的日期操作,我建议使用moment.js
(减少头痛,提高一致性,减少测试,简化维护).
For more advanced date manipulations, I recommend moment.js
(less headaches, better consistency, less testing, simpler maintaining).
编辑:已添加:
date_expression | date[:format[:timezone[:locale]]]
代码: https://github.com/angular/angular/blob/5.0.4/packages/common/src/pipes/date_pipe.ts#L137 文件: https://angular.io/api/common/DatePipe
这篇关于如何使用Angular 4日期管道处理时区问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!