Juneikerc.com

Calculate how many days there are between two dates using JavaScript

Featured image of the post: Calculate how many days there are between two dates using JavaScript

Do you need to calculate how many days there are between two specific dates using JavaScript? In this post, I'll show you how you can do it in just a few lines of code.

Step by Step

We declare two variables with the dates from which we want to obtain the difference in days.

js
let date1 = new Date("01/01/2022");
let date2 = new Date("12/24/2022");

We obtain the number of milliseconds between the two dates using the .getTime method of the Date() object, subtracting the milliseconds of date 1 from those of date 2.

js
let difference = date2.getTime() - date1.getTime();

Finally, we obtain the difference between the two numbers and divide it by the milliseconds contained in a day.

js
let daysDifference = difference / 1000 / 60 / 60 / 24;
console.log(daysDifference); // result: 357
Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me