我有一個腳本,我想檢查該腳本上次運行的時間。因此,我在腳本結束之前在作業表中記錄“上次運行”日期時間,并在每次腳本啟動時提取資料。但是,當我將當前日期與上次運行日期進行比較時,計算總是錯誤的。
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());
輸出是
1:57:21 PM Info December 10, 2021 01:57:21 0800 Asia/Hong_Kong
在 1:57PM 運行腳本如何回傳 01:57:21 0800 ?不應該是 13:57:21 0800 嗎?
uj5u.com熱心網友回復:
我發現了這個問題。我記錯時間了。
而不是使用'MMMM dd, yyyy hh:mm:ss Z',我應該使用'MMMM dd, yyyy HH:mm:ss Z'
uj5u.com熱心網友回復:
您不能直接從另一個日期“減去”一個日期。
您必須先將日期轉換為毫秒。然后您可以從另一個日期中減去一個日期,然后您必須將差異轉換為分鐘或小時。
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());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380442.html
標籤:javascript 日期 谷歌应用程序脚本
