How to compare two dates in Javascript

In this tutorial, we are going to see how to compare two dates. In JavaScript we can compare two dates by converting them to a numeric value to match the times, for this we use the getTime() function. By converting the specified dates into numeric values, we can compare them directly.

We can use the relational operators below to compare two dates:


We cannot apply these operators below on the Date object, but you can use it with the date.getTime() method:


Example 1:
var date1 = new Date('2020-01-25');
var date2 = new Date('2020-01-20');

if(date1 > date2){
    document.write('date1 is greater than date2');
    document.write('date1 is less than date2');


date1 is greater than date2


Example 2:
var date1 = new Date('2020-01-20');
var date2 = new Date('2020-01-20');

if(date1.getTime() == date2.getTime()){
    document.write('date1 and date2 are equal');
    document.write('date1 and date2 are not equal');


date1 and date2 are equal
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *