[英]Compare two dates, one from New data() and another from text
我有一個腳本,我想檢查腳本上次運行的時間。 因此,我在腳本結束之前將“上次運行”日期時間記錄在一張表中,並在每次腳本啟動時提取數據。 但是,當我將當前日期與上次運行日期進行比較時,計算總是錯誤的。
var dtToday = new Date();
var dtDebug=new Date(shtYahooDataRef.getRange(2,2).getValue()); //This is extra code for my debugging
var dtLastUpdate=new Date(shtYahooDataRef.getRange(1,2).getValue()); //This is where I retrieve the last ran datetime
// Just to check that the dates are correct
Logger.log (Utilities.formatDate(dtToday, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
Logger.log (Utilities.formatDate(dtDebug, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
Logger.log (Utilities.formatDate(dtLastUpdate, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
//Given that dtToday and dtDebug are very close, I expect the below to be very close but this is not case. Hence I wonder why
Logger.log (dtToday-dtLastUpdate);
Logger.log (dtDebug-dtLastUpdate);
這是日志
December 07, 2021 02:26:25 +0800
December 07, 2021 02:26:13 +0800
December 07, 2021 02:25:13 +0800
4.3272544E7
60000.0
dtToday-dtLastUpdate
和dtDebug-dtLastUpdate
如此不同? dtToday-dtLastUpdate
不會在 60000 的范圍內嗎?
附加信息。 如果上次運行時間少於 6 小時前,這是我退出腳本的實際代碼。 條件總是錯誤的。
var t1 = dtToday.getTime(),
t2 = dtLastUpdate.getTime();
if ( Math.floor((t1-t2)/(3600*1000))< 6) {
return;
}; // 3600*1000 is milliseconds in an hour Update only is last update was 6 hr ago
附加評論:如果我有一個簡單的腳本
var dtToday = new Date();
Logger.log (Utilities.formatDate(dtToday, "Asia/Hong_Kong", 'MMMM dd, yyyy hh:mm:ss Z')+" "+Session.getScriptTimeZone());
output 是
1:57:21 PM Info December 10, 2021 01:57:21 +0800 Asia/Hong_Kong
在下午 1:57 運行腳本如何返回 01:57:21 +0800? 不應該是 13:57:21 +0800 嗎?
我發現了這個問題。 我錯誤地記錄了時間。
而不是使用'MMMM dd, yyyy hh:mm:ss Z'
,我應該使用'MMMM dd, yyyy HH:mm:ss Z'
您不能直接從另一個日期“減去”一個日期。
您必須首先將日期轉換為毫秒。 然后你可以從另一個日期中減去一個日期,然后你必須將差異轉換為分鍾或小時。
var dtToday = new Date();
var dtDebug=new Date(shtYahooDataRef.getRange(2,2).getValue()); //This is extra code for my debugging
var dtLastUpdate=new Date(shtYahooDataRef.getRange(1,2).getValue()); //This is where I retrieve the last ran datetime
// Just to check that the dates are correct
Logger.log (Utilities.formatDate(dtToday, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
Logger.log (Utilities.formatDate(dtDebug, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
Logger.log (Utilities.formatDate(dtLastUpdate, Session.getScriptTimeZone(), 'MMMM dd, yyyy hh:mm:ss Z'));
//Given that dtToday and dtDebug are very close, I expect the below to be very close but this is not case. Hence I wonder why
Logger.log (dtToday.valueOf()-dtLastUpdate.valueOf());
Logger.log (dtDebug.valueOf()-dtLastUpdate.valueOf());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.