Compare two date formats in javascript/jquery

Roy M J picture Roy M J · Sep 20, 2013 · Viewed 108.9k times · Source

I have the following :

var fit_start_time  = $("#fit_start_time").val(); //2013-09-5
var fit_end_time    = $("#fit_end_time").val(); //2013-09-10

if(Date.parse(fit_start_time)>=Date.parse(fit_end_time)){
    alert("Please select a different End Date.");
}

The above code doesn't work. Is there any other solution to the above one?

formatting date as per Where can I find documentation on formatting a date in JavaScript? also dint work for me.

Answer

Elias Van Ootegem picture Elias Van Ootegem · Sep 20, 2013

It's quite simple:

if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
    //your code here
}

Comparing 2 Date instances will work just fine. It'll just call valueOf implicitly, coercing the Date instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date instances will be coerced to the Number type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.