How to calculate the difference between 2 dates in Javascript?

It would have been great if Javascript date objects could have been substracted like numbers.

const then = new Date();
const now = new Date();
const difference = now - then;

But unfortunately, that's not possible at this moment.

So what we can do instead, is to use getTime() on the date object and get the timestamp. A timestamp is the number of seconds passed since the Unix Epoch.

We can write,

const then = new Date();
const now = new Date();
const difference = now.getTime() - then.getTime();

This would give us the time difference between the 2 dates in seconds. Now if we wanted to convert this difference back to a date, we could do something like,

const then = new Date();
const now = new Date();
const difference = now.getTime() - then.getTime();
const aMoment = new Date(difference);

An example of where you might need to find the difference between 2 dates is while sorting an array by dates. Say we have an array of users,

const characters = [
    { name: 'Becca', 'born': new Date(2025, 1, 28) },
    { name: 'Clarke', 'born': new Date(2131, 9, 11) },
    { name: 'Belamy', 'born': new Date(2126, 11, 30) }
];

// Sort in descending order of date of birth
characters.sort((a, b) => b.born.getTime() - a.born.getTime());
console.log(characters);


Feliz Aprendizaje

Hashjar

Hashjar