JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Member-only story

How to Get the Number of Days Between Two Dates in JavaScript

A guide on how to get the number of days between 2 dates with JavaScript.

John Au-Yeung
JavaScript in Plain English
2 min readJan 25, 2022

--

Photo by Datingjungle on Unsplash

We often have to get the number of days between 2 dates in our JavaScript apps.

In this article, we’ll look at how to get the number of days between 2 dates with JavaScript.

Using String and Date Methods

We can calculate the number of days between 2 dates with JavaScript by using native string and date methods.

For instance, we can write:

const parseDate = (str) => {
const [month, day, year] = str.split('/');
return new Date(year, month - 1, day);
}
const datediff = (first, second) => {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
const diff = datediff(parseDate("1/1/2000"), parseDate("1/1/2001"))
console.log(diff)

We have the parseDate function that takes str date string in MM/DD/YYYY format.

We parse it by splitting the date string with '/' as the separator.

Then we get the year , month and day by destructuring.

And we pass all that into the Date constructor to return a date object.

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Responses (2)

Write a response