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?


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()) {
   ....
}

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();
    }
}