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_2 = new Date();
Then we’ll have to figure out what the difference is between these two dates.
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)
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_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.