Nov 11, 2010

Comparing Dates in Javascript

Javascript not only made life easy for Servers but made life hell for developers. Though it takes care of most of the computing stuff on the client side itself, it's behavior changes with respect to browsers. Comparing two dates using Java script is done quite frequently and doing it with the Date object doesn't work really the same on all occasions. One idea is to change the dates to a whole number and then compare them. If the two dates are 20-04-2009 and 25-03-2009, you can just invert them as 20090420 and 20090325 after removing the seperator. This will workout for all the date combinations.

Code for dd/mmm/yyyy format:

Assuming the arguments are in the format "dd/mmm/yyyy", the following function will return
  • 0 if d1 == d2, 
  • -1 if d1 < d2 and 
  • 1 if d1 > d2.
function compareDates(date1,date2) 
{
var d1 = date1.split("/").reverse(); 
var d2 = date2.split("/").reverse();
var months = { 'jan':'01', 'feb':'02' }; 
// ... You write the rest....till dec
d1[1] = months[d1[1]] || '00';
d2[1] = months[d2[1]] || '00';

date1 = d1.join("/");
date2 = d2.join("/");

return date1 == date2 ? 0 : date1 < date2 ? -1 : 1;
}
 

Code for dd/mm/yyyy format:

In this format, you don't have to convert months to its number equivalent. The task will be much simpler. Pass two string dates in DD/MM/YYYY format. This will return 0 if both are same, 1 of date1 is greater or -1 if smaller.

function compareDates(date1, date2) {
    var d1 = date1.split("/").reverse();
    var d2 = date2.split("/").reverse();
    var d1Num = Number(d1[0] + d1[1] + d1[2]);
    var d2Num = Number(d2[0] + d2[1] + d2[2]);
    return ((d1Num == d2Num) ? 0 : ((d1Num < d2Num) ? -1 : 1));
} 
 
If you have come across a better way, I will be interested in knowing it :)

You may also like these writeups

Related Posts with Thumbnails

Join our Gang