gpt4 book ai didi

javascript - 如何将 EST 中的日期字符串与 UTC 中的日期对象进行比较?

转载 作者:行者123 更新时间:2023-12-01 00:29:41 26 4
gpt4 key购买 nike

我正在尝试将 EST 中的字符串 8/26/2019 6:53:13new 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的作品。总是。您不必担心某些隐藏的时区组件会破坏它。只需比较您的日期,您就会发现它运行良好。

tl;dr:日期不是“格式”。日期就是日期。

关于javascript - 如何将 EST 中的日期字符串与 UTC 中的日期对象进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com