How to compare dates in JavaScript

About

A common task to do as a frontend developer is to process Date objects, and frequently that means to compare them. Today, I am going to show you the best way to compare dates and some tips that will help you to get the results you expected. This is very important because for example if you want to develop a method that sorts by a Date property, I am pretty sure you will face this issue and you will spend too many hours trying to figure out the actual reason about the error.

The problem

Imagine, you have two JavaScript Date objects like:

var a = new Date('2013-11-05');
var b = new Date('2013-11-05');

Then, you want to compare them, so you would probably think this code will print "a equals b":

if(a == b) {
	console.info("a equals b");
} 
else {
	console.log("a NOT equals b");
}

But my friend I have a bad new for you, previous code will always print "a NOT equals b", because Dates cannot be compared as simple types.

Solution

Instead of comparing dates using the operators directly, a good practice is to compare the dates but using the milliseconds format. You can obtain milliseconds format using the getTime( ) function.

if(a.getTime() == b.getTime()) {
	console.info("a equals b");
} 
else {
	console.log("a NOT equals b");
}

Now, the result is correct, previous code will print "a equals b".

Creating dates from String (parsing to Date)

Now, let's explore another common issue when we work with JavaScript Dates. Imagine you have a list of strings and you want to parse them in order to apply a sort( ) function, well in this case the best way to parse your strings into Date is to use the ISO-8601 format. Following list is an example of String in ISO-8601 that can be transformed to Date without any problem:

var dates = new Array("2014-06-03T08:00:00", "2014-12-03T10:44:22", "2014-06-22T10:00:00");
 
for(var i=0, datesLength = dates.length; i < datesLength; i++){ 
	var tempDate = new Date(dates[i]);
	console.info("Milliseconds:", tempDate.getTime());
}

About the author

Enterprise Web Developer

Alex is an experienced technology professional. His background includes:

  • Web Technologies: Semantic Web (RDF, OWL), MVC Frameworks (CakePHP, CodeIgniter) Content Management Systems (Drupal, Joomla, WordPress), JavaScript libraries (jQuery, Mootools), CSS3, HTML5, mobile web (Sencha, jQuery mobile), Operating Systems, and,
  • Research: Complex Systems (Cellular Automata in specific), Artificial Intelligence, Computer Graphics and Computer Simulation to create computer models of living.