如何从 javascript 中的日期字符串获取本地时区日期?

How to obtain a local timezone Date from a date string in javascript?

我正在建立一个在线商店,我的大部分客户(基本上所有)都位于给定的时区,但我的基础设施位于其他时区(我们可以假设它是 UTC)。我可以让我的客户选择 select 他们的订单日期,问题是我的日期组件代表这样的日期“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”。我该怎么做?

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

但请注意,像这样手动操作 timezone/offsets 可能会导致显示不正确的数据。

如果您仅以 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