In this article, we will learn how to find the number of days between two dates using Javascript.
But why do we need this functionality? what are its applications, Let understand this first, this is useful in many scenarios which are as follows:-
- Deadline Tracking
- Task Scheduling
- Hotel Reservation
- Medication Scheduling
- Attendance Tracking
Let’s see how we can find the number of days between two dates in javascript
Step 1:-
Define the two dates, for this tutorial I am defining statically you can take it dynamically as well using the document object model from HTML page.
const from_date = new Date('2024-08-01'); const to_date = new Date('2024-08-20');
Step 2:-
Calculate the difference in time (time is in milliseconds)
const timeDifference = to_date - from_date;
Step 3:-
Convert the time that we are storing in timeDifference
variable from milliseconds
to days
const days_between = timeDifference / (1000 * 60 * 60 * 24);
Step 4:-
At last, we are printing the output:-
console.log(days_between);
Output:-
19