Go to homepage

Projects /

How to compare dates in JavaScript

A tutorial on using the Date() object and its methods to perform date comparison in JavaScript.

How to compare dates in JavaScript
By CodyHouse
404 HTML, CSS, JS components. Download →

In this article, we want to explore the various methods for comparing dates in JavaScript, using the Date object and its associated methods. We'll provide this with real-world examples to demonstrate the practical applications of these methods.

Date comparison using the Date object #

The Date object can be used in JavaScript to perfom date comparison. You can create a Date object using the Date() constructor:

var date = new Date('2023-07-13');

You can pass, to the Date() constructor, a string rapresenting a date in the format YYYY-MM-DDTHH:mm:ss.sssZ, where:

  • YYYY is the year;
  • MM is the month (01-12);
  • DD the day of the month (01-31);
  • T is used to separate date from time;
  • HH is the hour (00 - 23);
  • mm is the minute (00 - 59);
  • ss is the second (00 - 59);
  • sss is the millisecond (000 - 999);
  • Z is the time zone.

Not all components are required; for example the followings are both valid Date objects:

var date = new Date('2023-07-13');
var date = new Date('2023-07-13T12:10:22');

If you do not pass any strings to the Date() constructor, then the created Date object will represent the current date:

var currentDate = new Date();

Once two dates have been created using the Date() constructor, they can be compared using the '>' or '<' operators:

var date1 = new Date('2023-07-13');
var date2 = new Date('2023-07-15');

if(date1 < date2) {
  // date1 is before date2
} else if (date1 > date2) {
  // date1 is after date2
} else {
  // date1 and date2 are the same date
}

An important point to note is that while we can use the '<' and '>' relational operators to compare dates in JavaScript, the equality operators such as '===' cannot be used. This is not an issue with the Date object itself, but rather a characteristic of how objects operate in JavaScript.

If you need to use an equality operator to compare dates, then you can use the getTime() method of the Date object.

Comparing dates using the getTime method #

The getTime() method, when applied to a Date object, returns the number of milliseconds that have passed since a specific moment in the past.

var milliseconds = new Date('2023-07-13').getTime();

You can get the time (in milliseconds) for both dates you want to compare, and then use the equality or relational operators to compare them:

var date1ms = new Date('2023-07-13').getTime();
var date2ms = new Date('2023-07-15').getTime();

if(date1ms < date2ms) {
  // date1 is before date2
} else if (date1ms > date2ms) {
  // date1 is after date2
} else {
  // date 1 and date2 are the same date
}

// but this also works
if(date1ms === date2ms) {
  // date1 and date2 are the same date
}

Additional methods to compare dates in JavaScript: getHours, getDay, getMonth, getFullYear #

There might be cases where you need to compare specific attributes of a date, such as the year. The Date object provides dedicated methods for such comparisons. For example, the getFullYear() method returns the year of a date:

var year = new Date('2024-12-15').getFullYear(); // this will return 2024

Similarly, you can get the other values of a date, for example the day or the month, using the methods getDay() or getMonth():

var month = new Date('2024-12-15T12:10:22').getMonth();
var day = new Date('2024-12-15T12:10:22').getDay();
var hours = new Date('2024-12-15T12:10:22').getHours();

Real-life examples #

Let's see these methods in action in some real-life examples.

Countdown component #

Take a look at this countdown component.

It shows the time remaining until a specified future date. For it to work, you need to compare two dates: the current date and a future date when a specific event will occur. You then need to display the difference between the two dates.

First step to achive this is to create two Date objects:

var dateNow = new Date();
var dateInTheFuture = new Date('2024-12-31'); // this value will change based on when your future event will happen.

Then we can get the difference (in milliseconds) using the getTime() function:

var dateNowMs = dateNow.getTime();
var dateInTheFutureMs = dateInTheFuture.getTime();
var msRemanining = dateInTheFutureMs - dateNowMs;

From this difference, you can get the number of days/minutes/seconds remaining. For example, the number of days will be:

var days = parseInt(msRemanining / 86400);

If you also want to show the hours, then:

var days = parseInt(msRemanining / 86400);
msRemanining = (msRemanining % 86400); // update the number of milliseconds removing the days (in milliseconds) from the original difference
var hours = parseInt(msRemanining / 3600);

Date Range component #

Take a look at this date range component.

It allows users to select a range of dates from a calendar widget. This component has many features implemented using the Date object and its methods. One of this is making sure the end date the user selects follows the start date.

An isPast() function can be used for that:

function isPast(startDate, endDate) {
  // check startDate is before endDate
  var startDateObj = new Date(startDate),
    endDateObj = new Date(endDate);
  return startDateObj < endDateObj;
};

Each time the user selects an end date, this function can be used to check if that date is a possible choice (which means, startDate is before the selected endDate).

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.