How do I get the number of days between two dates in JavaScript?


This tutorial teaches us to find the number of days between the two dates in JavaScript. If you are a developer, sometimes you face the scenario where you need to find the number of days between 2 dates.

For example, if you are building a software application to keep track of employees' attendance and salary. If an employee leaves without completing the month, you need to count the number of days the employee attended in the current month to give the salary. Furthermore, there can be many scenarios like the above example.

In this tutorial, we will see the different methods to find the number of days between the two dates.

Using the Date Class

We will use the Date class in JavaScript to achieve our goal in this approach. The object of the date class, new Date(), returns the total milliseconds starting from 01 / 01 / 1970.

We will create two new date objects and initializes them with our dates. Also, we will use the getTime() method to get the time difference between two dates.

Syntax

Users can follow the below syntax to initialize the data object with the current date.

let startDate = new Date( Date );
let endDate = new Date( end_date );
startDate.getTime() – endDate.getTime() // returns time difference in milliseconds.

Parameters

  • Date − As a Date parameter, users need to pass the date in the mm / dd / yy format.

Algorithm

Users can follow the below algorithm to get the number of days between 2 dates.

  • Step 1 − Initialize two date objects. One with starting date and another with end date.

  • Step 2 − Find the time difference between start and end dates in the milliseconds using the getTime() method of the Date class.

  • Step 3 − Divide the time difference with the total milliseconds in the single day which is (1000 milliseconds *60 seconds *60 minutes *24 hours).

  • Step 4 − In the above step, we will get the fractional days. We will use the Math.floor() function get the complete days.

Example

In the below example, we have implemented the above algorithm to find the number of days between the two dates in JavaScript.

<html>
<head>
   <title>Finding the number of days between 2 dates.</title>
</head>
<body>
   <h2>Finding the number of days between 2 dates.</h2>
   <h4>Total number of days between the 05/ 10/ 2022 and 06 / 21 / 2022</h4>
   <div id="days"></div>
   <h4> Total number of days between the 03 / 21 / 2021 and current date.</h4>
   <div id="currentdays"></div>
   <script type="text/javascript">
      let days = document.getElementById("days");
      let currentdays = document.getElementById("currentdays");

      // finding difference between 2 dates.
      let start_Date = new Date('05/ 10/ 2022');
      let end_Date = new Date('06 / 21 / 2022');

      // calculating total time difference
      let timeDifference = start_Date.getTime() - end_Date.getTime();
      let dayMilliSeconds = 1000 * 60 * 60 * 24;
      let totalDays = Math.abs(timeDifference / dayMilliSeconds); // it returns negative value if start date < end date
      totalDays = Math.floor(totalDays); // to get complete days
      days.innerHTML = totalDays;

      // finding difference between current date and other date
      let todaySDate = new Date(new Date().toISOString().slice(0, 10));
      let currentDiff = new Date('03 / 21 / 2021') - todaySDate;
      totalDays = Math.abs(currentDiff / dayMilliSeconds);
      currentdays.innerHTML = Math.floor(totalDays);
   </script>
</body>
</html>

The above output shows us difference between the current date and other date. Also, we can see the difference between two dates in the output.

Using the diff() Library Function of Moment JS

The Moment JS is the excellent library of JavaScript used to validate and manipulate the date and time in the JavaScript. We will add the CDN of the Moment JS library in the <head> section of our HTML code to use it with the Vanilla JavaScript.

The Moment JS has a built-in method called diff() to calculate the number of days between the two dates.

Syntax

Users can follow the below syntax to use the diff() method of Moment JS.

let start_Date = moment([2018, 1, 29]); // add date in the yy / mm / dd format.
let totalDays = end_Date.diff(start_Date, 'days');

Parameters

  • end_Date − It is a ending date.

  • Start_Date − It is a starting date.

  • days − To get the difference between two dates in days.

Example

In the below example, we have added the CDN to use Moment JS library in the vanilla JavaScript. After that we have create two date object using the Moment class and apply the diff() method to the dates.

<html>
<head>
   <title> Finding the number of days between 2 dates. </title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment-with-locales.min.js"
integrity="sha512-vFABRuf5oGUaztndx4KoAEUVQnOvAIFs59y4tO0DILGWhQiFnFHiR+ZJfxLDyJlXgeut9Z07Svuvm+1Jv89w5g=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
   <h2>Finding the number of days between 2 dates. </h2>
   <h4> Total number of days between the 29/ 01 / 2018 and 08 / 04 / 2022 using Moment Js</h4>
   <div id="days"> </div>
   <script type="text/javascript">
      let days = document.getElementById("days");
      // finding difference between 2 dates usign Moment Js.
      // create new date in the format of yy / mm / dd
      let start_Date = moment([2018, 0, 29]);
      let end_Date = moment([2022, 4, 08]);
      let totalDays = end_Date.diff(start_Date, 'days');
      days.innerHTML = totalDays;
   </script>
</body>
</html>

In the above output, users can see it shows number of days between two dates.

Conclusion

In this tutorial, we have seen two methods to find the number of days between two. There can be many methods available to achieve our goal. In the first method, we have used pure JavaScript, and in the second method, we have used the Moment JS library method. The second method is the best approach as users don’t need to write too much code.

Updated on: 20-Jul-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements