This page looks best with JavaScript enabled

Find difference between dates in days in Javascript

 ·   ·  ☕ 2 min read

Easy and right ways to calculate difference between two dates in Javascript.

Problem

We are given two dates and we have to print the difference between those two dates in days. Since we are given two valid dates, half of our problem is already gone and we have not started yet.

Get started

Calculate number of days - simple and plain.

1
2
3
4
5
const from = new Date(2019, 0, 1);
const to = new Date(2020, 0, 1);

console.log((to - from) / (1000 * 3600 * 24));
// 365

Date in Javascript is in millseconds since 1970. So the difference between two date objects is a big millisecond number. We just convert that to days.

1 day = Y ms / (1000 milliseconds in 1 second _ 3600 seconds in 1 hour _ 12 hours in a day)

Consider UTC

Dates can be from different time zones or have day light savings at different times. So, it may be a good idea to convert them to UTC and find the difference between UTC dates.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const from = new Date(2019, 0, 1);
console.log("from: ", from);
const to = new Date(2020, 0, 1);

const realFrom = Date.UTC(from.getFullYear(), from.getMonth(), from.getDate());

console.log(new Date(realFrom));
// 2019-01-01T00:00:00.000Z

const realTo = Date.UTC(to.getFullYear(), to.getMonth(), to.getDate());

console.log((realTo - realFrom) / (1000 * 3600 * 24));
// 365

Be careful about the subtraction

If you are not sure about which one of the dates is more recent, you can use math functions to find absolute difference. While you are at it, also use a different Math function to round off to nearest (lower) whole number.

1
2
console.log(Math.floor(Math.abs(realTo - realFrom) / (1000 * 3600 * 24)));
// 365
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things