Find the number of days between two dates in JavaScript

Photo by Nathan Dumlao on Unsplash

Our purpose of this tutorial is to find the number of days between two dates.

In JavaScript, we can create a date object using the Date() constructor. By default, it will display the browser’s timezone.

var today = new Date()
//Tue Oct 13 2020 21:58:37 GMT+0530 (India Standard Time)

Now, suppose we want to check the date of 1 January 2020. There are various methods to find it out. But, the most convenient way, I feel is given below.

var start = new Date("january 1,2020");//Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)

JavaScript Stores Dates as Milliseconds

JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated).

Suppose you want to see how many milliseconds have been passed since January 01, 1970, till now or till any date.

You can use getTime() method.

var today = new Date();
console.log(today.getTime());
//1602606920593

So, we have actually established our foundation for the Date object. Now, we can compute the no of days between “January 01, 2020” and today.

var start = new Date("January 1,2020");var today = new Date();// Number of milliseconds in a day
var day = 1000 * 60 * 60 * 24;
var diff = today - start;console.log(diff); // 24790433971console.log(Math.floor(diff / day) + " days from January 1, 2020"); //286 days from January 1, 2020

--

--