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?
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 withsubstrings()
to get the data you need but I guess this is not a very elegant way to proceed ;-)I did a little work around, not so charming but it seems to serve.
I´ll check out the other answers as well and give it a spin.
The
Date
object has thevalueOf
method which returns the number of milliseconds since midnight 1970-01-01. You can use it to compare dates. Something likeWow, 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:
If you're grabbing a value from your spreadsheet, just place the value into the new Date():
Somebody posted this a while back, I find it's very helpful