This is a short and simple guide on how to compare two dates in JavaScript. This is useful if you need to figure out which date is greater or which date occurred first.
Firstly, let’s create two JavaScript Date objects:
//Example date one. var dateOne = new Date('2019-01-01'); //Example date two. var dateTwo = new Date('2012-03-02');
As you can see, the first date is greater than the second date because it occurred nearly seven years later. However, what if we need to compare these two dates using JavaScript?
The getTime() method.
The getTime() method allows us to get the Unix Timestamp of a Date object. This method will return the number of milliseconds that have passed between the “Unix Epoch” and the date in question. Essentially, it will give us a numerical value that we can do some quick comparisons with.
Take a look at the following JavaScript code:
//Our IF / ELSE statement, which compares the dates //and prints the comparison results to the console. if(dateOne.getTime() > dateTwo.getTime()){ console.log('The first date is greater than the second date.'); console.log('The first date occurs after the second date.'); } else if(dateOne.getTime() > dateTwo.getTime()){ console.log('The second date is greater than first date'); console.log('The second date occurs after the first date.'); } else{ console.log('These two dates are the same.'); }
Above, I created a simple IF/ELSE statement that compares the Unix Timestamp of each Date object. If the timestamp of date one is greater than the timestamp of date two, then it means that date one occurred later. This is because more milliseconds have passed between the Unix Epoch and date one than the Unix Epoch and date two.
If you run the code snippet above, you will see that the first IF statement is proven TRUE and that the following output is logged to the browser’s console:
The first date is greater than the second date. The first date occurs after the second date.
This is because the date “2019-01-01” is greater than “2012-03-02”.
By the way, there is no need to stick to the YYYYMMDD format. You can also create a Date object using a date string like so:
//Creating a Date object using a different string format. var myDate = new Date('April 20, 2015');
Note that the getTime() method is also useful because it will return the timestamp in a UTC format. This means that we shouldn’t run into any annoying issues with timezones while comparing dates.
That’s it! Feel free to modify the dates above and see how it changes the console output!