Javascript Date Compare

I needed to validate if an end date was greater than or equal to a start date. To do this I was using:

var elemFromVal = $('#elemFromVal').val();
var elemToVal = $('#elemToVal').val();
return elemFromVal <= elemToVal;

This was working up until the point the years where different. For example “12/1/2010” to “12/2/2010” would work but not “12/1/2010” to “1/1/2011”.

To fix this issue I needed to create a new date object and compare those instead:

var elemFromVal = $('#elemFromVal').val();
var elemToVal = $('#elemToVal').val();

var d1=elemFromVal.split('/');
var d2=elemToVal.split('/');

var startDate=new Date(d1[2],(d1[1]-1),d1[0]);
var endDate=new Date(d2[2],(d2[1]-1),d2[0]);

return startDate <= endDate;
Advertisements