如何从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”。我该怎么办?

解决方法

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

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

如果仅在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