[英]How do I compare a Date string in EST with a Date object in UTC?
我正在嘗試將 EST 中的這個字符串8/26/2019 6:53:13
與new Date()
object 進行比較,以簡單地查看它是否在過去。 這在本地工作正常,但在部署時 heroku 的新日期以 UTC 格式出現。 所以我不得不做這個黑客
if(process.env.NODE_ENV){
timeSubmitted.setHours(timeSubmitted.getHours() + 5); // HACK but does work
}
我試圖以 UTC 格式獲取今天的日期和時間,因為 object 不是字符串,因此我可以將其與 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:日期不是“格式”。 日期就是日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.