• Post category:JavaScript
  • Reading time:3 mins read

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.

Use the following JavaScript function to get the number of days between two dates.

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

  1. Get the value of two dates.
  2. Initialize them by creating the date objects using new Date().
  3. Calculate the time difference of two dates using dt2.getTime() - dt1.getTime().
  4. Calculate the no. of days by dividing total milliseconds (1000 * 60 * 60 * 24).
  5. 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..!! 🙂

Leave a Reply