How to Compare Two Date Objects in Javascript

The best way to compare 2 Date objects using javascript is to get its long equivalent.

For example we have a date in this format: mm-dd-yyyy and we want to compare them. We will declare the javascript function this way:

function compareDate(a, b) {
 var temp, from, to;
 
 from = new Date();
 temp = a.split("-");
 from.setFullYear(temp[2], temp[0] - 1, temp[1]);
 
 to = new Date();
 temp = b.split("-");
 to.setFullYear(temp[2], temp[0] - 1, temp[1]);
 
 if(from.getTime() > to.getTime()) {
  return false;
 }
 return true;
}

For setFullYear's definition:
http://www.w3schools.com/jsref/jsref_setfullyear.asp

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.