javascript - 如何将 EST 中的 Date 字符串与 UTC 中的 Date 对象进行比较?
问题描述
我正在尝试将8/26/2019 6:53:13
EST 中的这个字符串与一个new Date()
对象进行比较,以简单地查看它是否在过去。这在本地工作正常,但在部署时 heroku 的新日期以 UTC 格式出现。所以我不得不做这个黑客
if(process.env.NODE_ENV){
timeSubmitted.setHours(timeSubmitted.getHours() + 5); // HACK but does work
}
我试图以 UTC 格式获取今天的日期和时间作为对象而不是字符串,以便我可以将其与 UTC 格式的其他时间进行比较。
var date = new Date('2014-02-27T10:00:00')
//Thu Feb 27 2014 10:00:00 GMT-0500 (Eastern Standard Time) //this is an object
let d = moment.utc(new Date()).format()
//Does convert right now to a UTC time string, but then when I try convert it to an object
new Date(d)
//it goes back to EST
所有这些确实有效,但由于硬编码的数字 5 并不理想。
//SET DATE RANGE
const startDate = new Date();//This gets converted from EST to UTC
startDate.setMinutes(startDate.getMinutes() - 2); //Google spreadsheets saves minutes a little in the past
//startDate = new Date(startDate.getTime() + startDate.getTimezoneOffset() * 60000);
const endDate = new Date();
endDate.setDate(endDate.getDate() + 5)
console.log('startDate ' ,startDate,'endDate ',endDate)
rows.forEach(row=>{
//row.timestamp looks like this '8/26/2019 6:53:13' in EST
var date= row.timestamp.split(" ")[0].split('/')
var time=row.timestamp.split(" ")[1].split(':')
var timeSubmitted = new Date(date[2], date[0] - 1, date[1], time[0], time[1], time[2]); //So this is in EST
//but then when deploying to heroku i had to do this hack.
if(process.env.NODE_ENV){
timeSubmitted.setHours(timeSubmitted.getHours() + 5); // HACK -- It's the only way I could get this time to be in UTC/timeSubmitted = new Date(timeSubmitted.getTime() + timeSubmitted.getTimezoneOffset() * 60000);
}
console.log('timeSubmitted',typeof timeSubmitted, typeof startDate, timeSubmitted, startDate, timeSubmitted >= startDate, timeSubmitted < endDate)
if(timeSubmitted >= startDate && timeSubmitted < endDate){ //Within the date range so check if the names are in the roster
slackers = slackers.filter(function(a){return a.fullname !== row.whatsyourname})
}
})
messageSlackers(slackers, id)
解决方案
时区只是从日期生成人类可读字符串时考虑的一个因素。
但是日期是一个时间点,与时区无关。时间不知道时区!人类发明了时区。
您可能正在Date
以某种方式对您的对象进行字符串化,默认情况下使用您的本地时区(没有向我们展示此代码)。这没关系。
比较两个Date
s 的作品。总是。您不必担心某些隐藏的时区组件会破坏它。只需比较您的日期,您就会发现它运行良好。
tl; dr:日期不是“格式”。日期就是日期。
推荐阅读
- java - 在java中,输入文本并将它们放入二维字符数组中
- javascript - Angular8 - 将模型作为带有单独字段的发布请求发送
- python - 动态分配唯一值 - Python
- go - golang中的类型转换
- c# - 与不同域中的 WCF 服务通信
- vba - Outlook 电子邮件对话的最后一个元素不会触发 VBA 中的 Application_ItemLoad 事件
- matlab - 我可以使用不同的循环来执行此操作,以及如何使其成为函数?
- javascript - 为网站创建 google 登录,但收到“错误:invalid_client 未找到 OAuth 客户端”。错误
- python - 以特定时间间隔运行脚本
- android - Android:来自 Firebase 存储的音频流使用了太多数据