首页 > 解决方案 > Angular date object setting hour causes date to be day before

问题描述

When I run these two lines:

date_obj = new Date('2018-08-23');
date_obj.setHours('19');

The output I get is:

2018-08-23T00:00:00.000Z

And then:

2018-08-22T23:00:00.000Z

I understand that it's being changed to UTC time in the second one hence the hour being 23 and not 19 like it was set to. So my question is why is it changing it to the day before and how can I stop this from happening?

标签: angulardatetime

解决方案


使用字符串参数调用Date 构造函数会创建一个 UTC 日期。如果您在 GMT-0400(东部),调用new Date('2018-08-23')会导致:

Eastern: 2018-08-22 20:00:00
GMT:     2018-08-23 00:00:00

当你打电话时,你根据当地时间Date.setHours(19)设置小时,结果是:

Eastern: 2018-08-22 19:00:00
GMT:     2018-08-22 23:00:00

您可以使用接受多个参数的Date 构造函数创建本地时间的日期:

let date = new Date(2018, 7, 23); // Note: the month index starts at zero

这使:

Eastern: 2018-08-23 00:00:00
GMT:     2018-08-23 04:00:00

然后调用Date.setHours(19)获取:

Eastern: 2018-08-23 19:00:00
GMT:     2018-08-23 23:00:00

请参阅此 stackblitz以获取演示。


推荐阅读