比较两个日期,一个来自New data(),另一个来自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-dtLastUpdatedtDebug-dtLastUpdate会如此不同?dtToday-dtLastUpdate不会在6万人的球场上吗?

其他信息。如果上次运行时间不到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点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());