How to calculate days between two dates in javascript?

In this blog of javascript, we will see to calculate the days between the two dates using javascript date functions.

As we will going to apply the following steps to calculate the days between two dates with the example.

  1. Firstly, we have to define the two javascript variables for 2 specific dates.
  2. Now, Initializing the defined variables by creating the date objects using new Date().
  3. After defining the dates, calculate the time difference between them by subtracting one date from another date using date2.getTime() – date1.getTime();
  4. The next step is to calculate the days between the dates. So, we will divide the time difference of both dates by the milliseconds in a day, i.e., 10006060*24
  5. At last, we will print the result calculated using the document.write() method.

Example :

<script>

  var date_one, date_two;

  //define two date object variables with dates inside it
  	date_one = new Date("04/18/2022");
  	date_two = new Date("04/25/2016");

  //calculate time difference
  var time_difference = date_one.getTime() - date_two.getTime();

  //calculate days difference by dividing total milliseconds in a day
  var days_difference = time_difference / (1000 * 60 * 60 * 24);

  document.write("Number of days between dates  < br > " + 
    date_one + " and  < br > " + date_two + "
    are: < br > "  + days_difference + " days");

</script>

OutPut :

Number of days between dates
Mon Apr 18 2022 00:00:00 GMT+0530 (India Standard Time) and
Mon Apr 25 2022 00:00:00 GMT+0530 (India Standard Time) are:
7 days

So, thanks for following this blog, and if you need any help please leave your queries in the comment box we will be happy to help you.

How to calculate days between two dates in javascript? expoundsofttechsolution ghb