Blog

How to Javascript compare dates

Working with dates in JavaScript can sometimes feel deceptively simple—until you try to compare them. Whether you’re developing a calendar, building a task manager, or validating user input, you’ll find that comparing dates is a fundamental skill. Knowing how to accurately and efficiently compare dates is essential in a wide array of JavaScript-based applications. In this article, we’ll explore the ins and outs of comparing dates in JavaScript, covering different types of comparisons, pitfalls to avoid, and best practices for accuracy and clarity.

TL;DR

In JavaScript, you can compare Date objects by converting them to timestamps using getTime() or with relational operators like >, <, or ===. However, be cautious! Direct equality checks between two Date objects won’t work as you might expect because they are objects, not simple values. To compare only the date portion (without time), you’ll need to manually normalize the values or use helper libraries.

Understanding JavaScript Dates

In JavaScript, the Date object is your go-to tool for handling date and time. You can create a date using the constructor:

const date1 = new Date('2024-06-01');
const date2 = new Date(); // current date and time

Every Date object represents a specific moment in time. Internally, JavaScript stores this as the number of milliseconds since January 1, 1970 (the Unix Epoch). This makes comparing two dates relatively straightforward if you use proper methods.

Basic Date Comparisons

You can directly compare two Date objects using their millisecond values. Here’s how you can do it using getTime():


const date1 = new Date('2024-05-01');
const date2 = new Date('2024-06-01');

if (date1.getTime() < date2.getTime()) {
    console.log("date1 is earlier than date2");
}

Alternatively, JavaScript allows you to use relational operators directly:


if (date1 < date2) {
    console.log("date1 is earlier than date2");
}

Important note: Even though this shorthand approach works, it’s internally calling valueOf() on both objects—which returns the timestamp. So both methods are valid, but the first is more explicit and often easier to read and maintain.

Why Direct Equality Fails

This is a common pitfall:


const date1 = new Date('2024-05-01');
const date2 = new Date('2024-05-01');

console.log(date1 === date2);  // false!

Though the dates look identical, this returns false because objects in JavaScript are reference types. Even if two Date objects represent the exact same time, they are not the same object. However, compare their timestamps and you get the correct result:

console.log(date1.getTime() === date2.getTime());  // true

Comparing Only Dates Without Time

If you’re only interested in the calendar date (ignoring time), you’ll need to normalize the times. One way is to zero out the time components:


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

const date1 = normalizeDate(new Date('2024-06-01T10:30:00'));
const date2 = normalizeDate(new Date('2024-06-01T22:15:00'));

console.log(date1.getTime() === date2.getTime());  // true

This approach ensures you’re only comparing the year, month, and day—ignoring the time completely.

Using Helper Libraries

Sometimes, it’s easier to rely on a library like date-fns, Moment.js, or Luxon to streamline your date comparisons. For example, with date-fns:


import { isBefore, isEqual } from 'date-fns';

const date1 = new Date('2024-05-01');
const date2 = new Date('2024-06-01');

console.log(isBefore(date1, date2));  // true
console.log(isEqual(date1, date2));   // false

Using libraries can save you a lot of time and reduce bugs, especially when dealing with tricky time zones, daylight saving time, or date arithmetic.

Common Use Cases for Comparing Dates

Let’s look at where this knowledge comes in handy:

  • Event scheduling: Prevent users from selecting past dates.
  • Form validation: Make sure an expiration date is after the creation date.
  • Activity logging: Sort or filter logs based on timestamps.
  • Reminders and deadlines: Notify users about upcoming due dates.

Sorting Arrays of Dates

Sorting is another scenario where date comparison becomes crucial. If you have an array of dates and want to sort them either ascending or descending:


const dates = [
    new Date('2024-06-01'),
    new Date('2024-05-01'),
    new Date('2024-07-01')
];

// Ascending
dates.sort((a, b) => a - b);

// Descending
dates.sort((a, b) => b - a);

Since subtracting two Date objects returns the difference in milliseconds, this technique works seamlessly with JavaScript’s array.sort() function.

Handling Time Zones

One tricky part of date comparisons is dealing with different time zones. JavaScript Date objects always contain a time and are converted to your local time zone by default. This can cause confusion when comparing dates across different systems or users in different regions.

To handle this, it’s best to:

  • Work with UTC using date.toISOString() or getUTCDate()
  • Use libraries that offer solid time zone support, like Luxon
  • Normalize all dates to a baseline time zone before comparing

Best Practices

Here are some best practices to follow when comparing dates in JavaScript:

  • Be explicit: Use getTime() or valueOf() for clarity
  • Normalize if you’re only comparing the date portion
  • Use libraries for more complex tasks like manipulating dates, handling time zones, etc.
  • Document your code: Future readers will thank you when you explain how and why you’re comparing dates

Conclusion

Although it might seem simple at first glance, comparing dates in JavaScript can be surprisingly nuanced. Understanding the behavior of Date objects, being mindful of how equality and relational operators work, and knowing when to use helper libraries will make your code more robust and reliable. Whether you’re building a to-do list or managing international scheduling, the ability to correctly compare dates is a vital part of your JavaScript toolkit.

So next time you find yourself asking whether one date is earlier than another, you’ll know exactly what to do—and how to do it right.