Monday, March 30th 2015
Today I was playing around with a date picker at work and ran across the question "can you compare two date objects cross browser" Luckily, I have an answer for you! Short answer: yes. The image above is Internet Explorer 7. Long answer:
You can create a new date object and compare them like this:
var olderDate = new Date(1994,03,19),
newerDate = new Date(2014,03,19);
if (newerDate > olderDate){
//works!
}
That works in the following browsers (as far as I can tell):
The real problem with this isn't actually comparing the objects. It's how the browsers create the date object differently. Creating an object by passing in a date string, say in ISO-8601 format, things get wonky.
var olderDate = new Date("1994-03-19"),
newerDate = new Date("2014-03-19");
if (newerDate > olderDate){
//some browsers work
}
IE7 gives us NAN. Safari 5.1, iOS Safari 5.0, and Android browser 2.3 all return "invalid date". Things get even weirder if you pass in a non ISO formatted date like "03-19-1994". Even less browsers, like older versions of firefox, say "invalid date".
So what I learned is to create date objects using the proper format MDN suggests:
new Date(year, month, day, hour, minute, second, millisecond);
You can download the two different sets of screenshots from browserstack here:
Heres the selected browsers:
Let's say your backend code is only giving you a string in ISO-8601 format. Don't fret! We can use the getTime()
method to get a numeric value from the date object according to universal time. For example new Date("03-19-1994").getTime();
you get 764053200000
back. Which is an number, not a string. You can use this to compare the two dates and it will work in pretty much all the browsers.