How To Compare Dates In Javascript

When working with date and time in JavaScript, you often need to compare different dates to determine their order or other relationships. In this blog post, we’ll go over how to compare dates in JavaScript and some common use cases.

Basic Date Comparison

In JavaScript, dates are represented by the Date object. To compare two dates, you can subtract one date object from another. This will give you the difference between the two dates in milliseconds. You can then use this value to determine which date is earlier or later.

Here’s a simple example:

const date1 = new Date(‘2021-01-01’);
const date2 = new Date(‘2021-01-10’);
const difference = date2 – date1;
console.log(difference); // 777600000

In the example above, difference will be positive if date2 is later than date1, and negative if date2 is earlier than date1.

Comparing Dates Without Time

Sometimes, you may want to compare dates without taking the time into account. To do this, you can create a new date object for each date with the time set to midnight.

function removeTime(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

const date1 = new Date(‘2021-01-01T12:00:00’);
const date2 = new Date(‘2021-01-01T15:00:00’);
const date1WithoutTime = removeTime(date1);
const date2WithoutTime = removeTime(date2);
const difference = date2WithoutTime – date1WithoutTime;
console.log(difference); // 0

In this example, the difference will be 0 if the two dates are the same, positive if date2 is later, and negative if date2 is earlier.

Common Date Comparisons

Here are some common date comparisons and how to perform them in JavaScript:

  • Check if two dates are the same:if (date1.getTime() === date2.getTime()) {
    console.log(‘Dates are the same’);
    } else {
    console.log(‘Dates are different’);
    }
  • Check if a date is before another date:if (date1 < date2) {
    console.log(‘Date1 is before Date2’);
    } else {
    console.log(‘Date1 is not before Date2’);
    }
  • Check if a date is after another date:if (date1 > date2) {
    console.log(‘Date1 is after Date2’);
    } else {
    console.log(‘Date1 is not after Date2’);
    }

Conclusion

Comparing dates in JavaScript is straightforward once you understand how the Date object works. By subtracting one date object from another, you can easily determine the order and relationship between two dates. Remember that you can also use helper functions to compare dates without their time component if needed.