Compare two dates Google apps script
Asked Answered
B

6

33

What would be the best way to compare two dates?

var int = e.parameter.intlistbox;
var startDate = rSheet.getRange(parseInt(int) + 1 ,1).getValues();
// returns Sat Jun 30 2012 00:00:00 GMT-0300 (BRT) 
var toDay = new Date();
// Sat Jun 23 2012 22:24:56 GMT-0300 (BRT)

if (startDate > toDay){ ....

I saw the .toString() option but that seems to work only for == or === operator.

Anything clear about this matter?

Beacham answered 24/6, 2012 at 1:39 Comment(1)
it depends WHAT you want to compare. What about the date do you want to compare?Crystallize
T
46

The Date object has the valueOf method which returns the number of milliseconds since midnight 1970-01-01. You can use it to compare dates. Something like

var date01 = new Date();
var date02 = new Date(2012, 5, 24);
if (date01.valueOf() > date02.valueOf()) {
   ....
}
Trustworthy answered 24/6, 2012 at 7:58 Comment(3)
How do you know this? What type (from what library) is Date? Can you link to its documentation?Suziesuzuki
@dinosaur, I know it by executing the code similar to var d0 = new Date(0); var d1 = new Date(1); var str0 = d0.toISOString(); var str1 = d1.toISOString();. As soon as it is executed the str0 has 1970-01-01T00:00:00.000Z value and str1 has 1970-01-01T00:00:00.001Z one. This code is executed in the GAS environment. I assume that GAS has no documentation for Date and other base classes inherited from JS. In similar way one can't find any reference to the String class in the GAS documentation.Trustworthy
That doesn't work for equal comparision since date01 has time and date02 time is 00:00:00Paralogism
D
22

Somebody posted this a while back, I find it's very helpful

function testDate() {
    var futureDate = new Date('8/31/2020');
    var todayDate = new Date();
    Logger.log(DateDiff.inMonths(todayDate, futureDate));
    Logger.log(DateDiff.inYears(todayDate, futureDate));             
}

var DateDiff = {    
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },
    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },
    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },
    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}
Darryldarryn answered 25/6, 2012 at 16:23 Comment(0)
S
6
// Date, Date -> Number
// Get the number of days between two dates

test("Date Diff In Days", 5, function(){
  ok(DateDiffInDays(new Date("January 1, 2000"), new Date("January 1, 2000")) == 0, "Ok");
  ok(DateDiffInDays(new Date("January 1, 2000"), new Date("January 2, 2000")) == 1, "Ok");
  ok(DateDiffInDays(new Date("January 1, 2000"), new Date("January 11, 2000")) == 10, "Ok");
  ok(DateDiffInDays(new Date("January 11, 2000"), new Date("January 1, 2000")) == -10, "Ok");
  ok(DateDiffInDays(new Date("January 1, 2000"), new Date("April 10, 2000")) == 100, "Ok");
});


function DateDiffInDays(a, b) 
{
  var _MS_PER_DAY = 1000 * 60 * 60 * 24;
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Struve answered 18/6, 2013 at 14:35 Comment(0)
G
6

Wow, I'm late here. I found it easiest to convert the dates into the integer Day of the year. So Jan 1st would be 1, Feb 1st would be 32, etc.

Here is that script:

today = parseInt(Utilities.formatDate(new Date(),"EST","D"));

If you're grabbing a value from your spreadsheet, just place the value into the new Date():

today = parseInt(Utilities.formatDate(new Date(rSheet.getRange(parseInt(int) + 1 ,1).getValues()),"EST","D"));
Gaptoothed answered 10/3, 2015 at 22:52 Comment(1)
This works if both the dates are in the same year. It fails if the dates are in different yearsTelethon
T
4

Date objects can be compared just as any other variables. The only tricky thing is if you need to compare two dates on the same day for example and expect to get date A = date B , in this case you have a problem since dates also include hours and minutes (and second + milliseconds) ! (that's why I suggested to use strings to check equality in the post you refer to). What you could do is to set hours, minutes, seconds and milliseconds to 0 in both variables so the comparison occurs on day, month, year only. See w3schools date reference page to see how to do that.

Another possibility would be to convert both dates to strings using Utilities.formatDate() and play with substrings() to get the data you need but I guess this is not a very elegant way to proceed ;-)

Thermit answered 24/6, 2012 at 7:57 Comment(0)
B
4

I did a little work around, not so charming but it seems to serve.

var startDate = rSheet.getRange(parseInt(int) + 1 ,1).getValues();
var toDay = new Date();

 var sYyyy = Utilities.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.formatDate(new Date(toDay), "GMT-2","MM");
 var tDd = Utilities.formatDate(new Date(toDay), "GMT-2","dd");


 if (sYyyy + sMm + sDd > tYyyy + tMm + tDd) {....

I´ll check out the other answers as well and give it a spin.

Beacham answered 25/6, 2012 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.