Comparing dates in JavaScript

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: July 11, 2022.

Getting the difference between or sorting dates in JavaScript is actually a comparison between timestamps. These are generated automatically when using the Date() constructor to create Date objects.

Table of contents

Date objects and timestamp

To compare dates, first create new Date objects using the in-built Date() constructor:

const earlier = new Date(1999, 00, 01);
const later = new Date(2022, 00, 01);

Under the hood, the Date() constructor converts this input into a Unix Timestamp: the amount of time that has elapsed since Jan 1 1970. In a JavaScript Date object, this is counted in milliseconds and is a Date object’s primitive value.

const earlier = new Date(1999, 00, 01);
const later = new Date(2022, 00, 01);

console.log(earlier.valueOf());
console.log(later.valueOf());

Getting the difference between two dates

Calculating timestamp differences

To calculate the time between two dates, all you need to do is directly compare Date objects, which is really a comparison between Unix timestamps:

const earlier = new Date(1999, 00, 01);
const later = new Date(2022, 00, 01);

/* Comparing date objects */
console.log(earlier === later); // false
console.log(earlier > later); // false
console.log(earlier < later); // true

/* The values being compared under the hood */
console.log(earlier.getTime()); // 915145200000
console.log(later.getTime()); // 1640991600000

Converting timestamp to other units

If you want to get the difference between two dates in a more conventional unit (e.g. days), you need to compare dates to get the milliseconds difference. Then convert to a more appropriate unit.

You can do this by dividing the difference in milliseconds by the multiplication of the larger time units the milliseconds spread across:

const earlier = new Date(1999, 00, 01);
const later = new Date(2022, 00, 01);

// Get difference in milliseconds
const diffMilliseconds = Math.abs(later - earlier);

// Divide difference by larger units multiplied
const diffDays = Math.round(diffMilliseconds / (1000 * 60 * 60 * 24)); 
const diffYears = Math.round(diffMilliseconds / (1000 * 60 * 60 * 24 * 365)); 

console.log(diffDays); // 8401
console.log(diffYears); // 23

Sorting multiple dates

Because the primitive values of Date objects are simple numeric timestamps, you can sort several dates using the sort() method:

const a = new Date(1999, 00, 01);
const b = new Date(2030, 00, 01);
const c = new Date(1900, 00, 01);
const d = new Date(1950, 00, 01);
const e = new Date(2000, 00, 01);

const datesArray = [a,b,c,d,e];

const sortedArray = datesArray.sort((a,b) => {
  return a-b;
});

console.log(sortedArray);
// [
//  "1899-12-31T23:00:00.000Z",
//  "1949-12-31T23:00:00.000Z",
//  "1998-12-31T23:00:00.000Z",
//  "1999-12-31T23:00:00.000Z",
//  "2029-12-31T23:00:00.000Z"
// ]

Related links