JavaScript

How to calculate the days between two dates in javascript?

Have you ever been in a similar scenario in which we are given the joining date of an employee who has resigned from his/her designation on a certain date and we want to figure out how many days he/she has worked with the company to calculate his/her salary. In such a situation JavaScript can help.

That was only one out of a gazillion possible scenarios that you can find yourself in, but there are other issues that can take place when dealing with real-life problems. Therefore, we will be discussing how we can easily solve this problem using javascript.

Calculate days between two dates using javascript

Let’s take a look at how we can calculate the number of days in javascript.

We’ll start by defining two date objects.

let date_1 = new Date('10/25/2021');
let date_2 = new Date();

Then we’ll have to figure out what the difference is between these two dates.

let difference = date_1.getTime() - date_2.getTime();
console.log(difference);

Now, the result is in milliseconds and we must convert this result to days. The formula for converting milliseconds into the days is:

(1000 milliseconds * (60 seconds * 60 minutes) * 24 hours)

let TotalDays = Math.ceil(difference / (1000 * 3600 * 24));
console.log(TotalDays + ' days to world Cup');

This will calculate the days between the given two dates.

Complete code

Following is the complete code for this problem:

let date_1 = new Date('10/25/2021');
let date_2 = new Date();

const days = (date_1, date_2) =>{
    let difference = date_1.getTime() - date_2.getTime();
    let TotalDays = Math.ceil(difference / (1000 * 3600 * 24));
    return TotalDays;
}
console.log(days(date_1, date_2) +" days to world cup");

Just run the file and see the output in your terminal, the output will be similar to the following:

Conclusion

Days can be calculated between two dates by first finding out the difference of time between the two given dates which is resulted in milliseconds and then by converting the milliseconds into the days. In this post, we have learned how we can easily calculate the dates between the two dates in javascript using the getDate() property of the Date object.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.