Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating difference between two dates in Google Apps Script

I am getting datetime from an API call like following-:

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.

like image 793
Gela Ram Avatar asked Nov 29 '17 04:11

Gela Ram


People also ask

How do I compare two dates in Google App Script?

formatDate(new Date(startDate), "GMT-2","yyyy"); var sMm = Utilities. formatDate(new Date(startDate), "GMT-2","MM"); var sDd = Utilities. formatDate(new Date(startDate), "GMT-2","dd"); var tYyyy = Utilities. formatDate(new Date(toDay), "GMT-2","yyyy"); var tMm = Utilities.

What is === in Google script?

Equality (==): a == b results in true if the value a is equal to value b. Strict equality (===): a === b results in true if the value a is equal to value b and their types are also the same. Inequality (! =): a !=


2 Answers

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);
like image 65
Sudhir Bastakoti Avatar answered Sep 18 '22 19:09

Sudhir Bastakoti


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.

like image 22
Cooper Avatar answered Sep 17 '22 19:09

Cooper