angular - 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?
解决方案
使用字符串参数调用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以获取演示。
推荐阅读
- android - 有什么方法可以在 kotlin 中创建具有不同颜色或不同样式的文本视图
- javascript - 单击Javascript中的选定列表时如何传递标题标签数据?
- c++ - ns3 错误:从 'const ns3::TcpOption*' 到 'ns3::TcpOption*' 的无效转换 [-fpermissive]
- python - 通过 Python 从 Cloud Storage 到 BigQuery
- javascript - 计算解析的整数差时得到 NaN
- sql - 将多行合并为 1 - 更新表
- amazon-web-services - 如何配置 aws 事件桥以将事件作为内部或私有(VPC)发送到 URL
- flutter - 加载 tflite 模型颤振时失去与设备的连接
- python - 如何在 django 信号中以编程方式更新 m2m 字段
- java - Spring + MySQL 记录被复制而不是更新