javascript - 如何从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
您可以通过在将字符串传递给 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
推荐阅读
- discord.js - 如何获取添加机器人的用户?
- postgresql - 从更新结果中选择...在 jOOQ 中返回
- nestjs - NestJs Mailer Module 发送电子邮件时出错
- c# - 如何递归获取类/树/json信息
- python - 使用 split 和 while 循环以及外部文本文件在 python 中出错
- python - 如何确定 GridSearchCV 中每个评分指标的最佳参数和最佳分数
- android - 在对话框之前显示 admob 的正确方法
- typescript - 根据方法中的其他参数推断参数类型
- python - 有什么方法可以加速 pyspark 中的缓存过程?
- javascript - Angular 6中的嵌套三元条件