Calculate number of days between two dates using JavaScript
📅May 9, 2022
Today, you’ll learn how to calculate number of days between two dates using JavaScript.
Sometimes, we need to calculate the number of days between two dates. Using getTime() function, we can easily do this task.
- How to get day name from Date in JavaScript
- Show/Hide Text Box using JavaScript and jQuery
- How to Copy to Clipboard in JavaScript
- How to get first N elements of an array in JavaScript
function getDays(startDate, endDate) {
const dt1 = new Date(startDate);
const dt2 = new Date(endDate);
const time_difference = dt2.getTime() - dt1.getTime();
const result = time_difference / (1000 * 60 * 60 * 24);
return result;
}
getDays('2022-05-01', '2022-05-11');
// Output: 10
How it works
- Get the value of two dates.
- Initialize them by creating the date objects using
new Date()
. - Calculate the time difference of two dates using
dt2.getTime() - dt1.getTime()
. - Calculate the no. of days by dividing total milliseconds (1000 * 60 * 60 * 24).
- Return the result.
With the help of this logic you can create an example where you can take two input fields with date picker and one button to calculate the number of days.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂