我正在建立一个在线商店,我的大多数客户(基本上所有)都位于一个给定的时区,但我的基础设施位于其他时区(我们可以假设它是UTC)。我可以让我的客户为他们的订单选择一个日期,问题是我的date组件表示这样的日期:"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”。我该怎么做呢?
发布于 2020-10-01 12:31:57
您试图实现的目标可以通过在将字符串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
https://stackoverflow.com/questions/64148624
复制相似问题