how to compare two string dates in javascript?
Solution 1:
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
Demo Jsfiddle
Recently found out from a comment you can directly compare strings like below
if ("2012-11-01" < "2012-11-04") {
alert ("Error!");
}
Solution 2:
You can simply compare 2 strings
function isLater(dateString1, dateString2) {
return dateString1 > dateString2
}
Then
isLater("2012-12-01", "2012-11-01")
returns true while
isLater("2012-12-01", "2013-11-01")
returns false
Solution 3:
Parse the dates and compare them as you would numbers:
function isLater(str1, str2)
{
return new Date(str1) > new Date(str2);
}
If you need to support other date format consider a library such as date.js.
Solution 4:
Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.
// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2
function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}
P.S. would have commented directly to vitran's post but I don't have the rep to do that.