首页 > 解决方案 > 如何从javascript中的日期字符串获取本地时区日期?

问题描述

我正在建立一个在线商店,我的大多数客户(基本上全部)都位于给定的时区,但我的基础设施位于其他时区(我们可以假设它是 UTC)。我可以让我的客户为他们的订单选择一个日期,问题是我的日期组件代表这样的日期“YYYY-MM-DD”。在我使用 Date 构造函数时,如下所示:

let dateString = "2019-06-03"
let date = new Date(dateString)
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString

问题是我希望从本地时区计算 UTC 表示,而不是相反。假设我位于 GMT-5,当我说let date = new Date("2019-06-06")我想查看 "2019-06-03T00:00:00.000 GMT-5" 时,ISOString 应该是 "2019-06-03T05:00:00.000Z"。我怎样才能做到这一点 ?

标签: javascriptdatetimezone-offset

解决方案


T00:00:00您可以通过在将字符串传递给 Date() 构造函数之前将字符串附加到 dateString 来完成您想要实现的目标。

但请注意,像这样手动操作时区/偏移量可能会导致显示不正确的数据。

如果您仅以 UTC 存储和检索所有订单时间戳,它将避免与时区相关的问题,您可能不需要像这样处理时间戳。

let dateString = "2019-06-03"
let date = new Date(dateString + "T00:00:00")
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString


推荐阅读