How to Calculate the Number of Days Between Two Dates in JavaScript?

To calculate the number of days between two dates in JavaScript,

  • Pass each date string to the Date() constructor as an argument to get the corresponding Date object.
  • Call the getTime() method on each date object to get the number of milliseconds corresponding to each date.
  • Calculate the difference of the two dates in milliseconds
  • Convert the milliseconds into days by dividing 24*60*60*1000

For example,

// Get the date object corresponding to each date string
const date1 = new Date('2023-03-20');
const date2 = new Date('2023-03-10');

// Calculate the difference in milliseconds
const diff = date1.getTime() - date2.getTime();

// Convert milliseconds into days
const days = diff/(24*60*60*1000);

// Print the difference
console.log('The diff between two dates in days is: ', days);

Output:

The diff between two dates in days is:  10

In this example, we have used the getTime() function to get the number of milliseconds for a given date.

But what are these milliseconds?

Actually, the getTime() method returns the timestamp(in milliseconds) for the specified date object.

The timestamp is the total number of seconds passed since January 1st, 1970 UTC. So, when we call the getTime() method on a date object, it gives us the total number of milliseconds passed since January 1st, 1970.

Therefore, if we want to get the exact difference between the two dates, we can calculate the difference of their timestamp values.

Notice that the getTime() method gives the timestamp in milliseconds, not in seconds.

For example,

// 20 March, 2023
const date = new Date('2023-03-20');

// Get the timestamp in milliseconds
const timestamp = date.getTime();

console.log(timestamp);
// Output: 👉 1679270400000

You can also use the valueOf() method in place of the getTime() method.

Just like the getTime() method, the valueOf() method does also return the timestamp in milliseconds.

For example,

// 20 March, 2023
const date = new Date('2023-03-20');

// Get the timestamp in milliseconds
const timestamp = date.valueOf();

console.log(timestamp);
// Output: 👉 1679270400000

What if the date string also contains the time component? Do I have to handle it explicitly?

No, you don’t have to write any explicit piece of code for that case. The Date() constructor and the getTime() methods take care of it.

For example,

// Get the date object corresponding to each date string
const date1 = new Date('2023-03-20T08:30:00');
const date2 = new Date('2023-03-10T16:45:00');

// Calculate the difference in milliseconds
const diff = date1.getTime() - date2.getTime();

// Convert milliseconds into days
const days = diff/(24*60*60*1000);

// Print the difference
console.log('The diff between two dates in days is: ', days);

Output:

The diff between two dates in days is:  9.65625

That’s all for this article. Thanks for reading!