javascript 计算 Google Apps 脚本中两个日期之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47545080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating difference between two dates in Google Apps Script
提问by Gela Ram
I am getting datetime from an API call like following-:
我从 API 调用中获取日期时间,如下所示:
2017-11-21T20:23:26+0000
2017-11-21T20:23:26+0000
Now I want to compare this with today's date and calculate the difference in number of days, how can i do that in google apps script.
现在我想将它与今天的日期进行比较并计算天数的差异,我该如何在谷歌应用程序脚本中做到这一点。
thank you for your help.
感谢您的帮助。
回答by Sudhir Bastakoti
i think you can do something like this,
我认为你可以做这样的事情,
var dt1 = new Date(), // today's date
dt2 = new Date("2017-11-21T20:23:26+0000"); // your date from API
// get milliseconds
var t1 = dt1.getTime(),
t2 = dt2.getTime();
var diffInDays = Math.floor((t1-t2)/(24*3600*1000));
// 24*3600*1000 is milliseconds in a day
console.log(diffInDays);
回答by Cooper
Here's days, minutes and hours with a different approach:
以下是采用不同方法的几天、几分钟和几小时:
function getDaysHoursAndMinutes(){
var hd=new Date('2017-11-21T20:23:26+0000').valueOf();
var td=new Date().valueOf();
var sec=1000;
var min=60*sec;
var hour=60*min;
var day=24*hour;
var diff=td-hd;
var days=Math.floor(diff/day);
var hours=Math.floor(diff%day/hour);
var minutes=Math.floor(diff%day%hour/min);
Logger.log('%s days %s hours %s minutes',days,hours,minutes);
}
The basic idea is that the value of a date is the number of milliseconds from a given date time reference which I think in this case is January 1, 1970.
基本思想是日期的值是给定日期时间参考的毫秒数,我认为在这种情况下是 1970 年 1 月 1 日。

