Categories
JavaScript Answers

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

Spread the love

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.

We’ve to subtract month by 1 to get the correct JavaScript month.

Then we calculate the date difference with the dateDiff method by subtracting the second by first .

When we subtract 2 dates, both dates will be converted to timestamps automatically before subtraction.

So we can subtract them directly.

And then we divide this by 1 day in milliseconds.

Finally, we round the division result with Math.round .

Now we can call all the functions we created to parse and get the date difference from the parsed dates.

And so we get diff is 366.

moment.js

We can use moment.js to get the difference between 2 dates easily.

For instance, we can write:

const start = moment("2000-11-03");
const end = moment("2001-11-04");
const diff = end.diff(start, "days")
console.log(diff)

We just pass the date strings into the moment function.

Then we call diff to get the difference between the moment date it’s called on and the moment date object we passed in.

The 2nd argument is the unit of the difference we want to return.

So diff is also 366 since the 2 dates differ by 366 days.

Conclusion

We can use native JavaScript string and date methods to compute the difference between 2 dates.

Also, we can use the moment.js library to make our lives easier.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *