Javascript Date Compare

Posted: December 1, 2010 in JavaScript

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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s