How to calculate the number of days between two dates in javascript?

Configurare noua (How To)

Situatie

Calculating the number of days between two dates in JavaScript required to use date object for any kind of calculation. For that, first, get the internal millisecond value of the date using the in-built JavaScript getTime() function. As soon as both the dates get converted, proceed further by subtracting the later one from the earlier one which in turn returns the difference in milliseconds. Later, the final result can be calculated by dividing the difference (which is in milliseconds) of both the dates by the number of milliseconds in one day.

Solutie

Pasi de urmat

Syntax:

Date.getTime()

Approach 1:

  • Define two dates using new Date().
  • Calculate the time difference of two dates using date2.getTime() – date1.getTime();
  • Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
  • Print the final result using document.write().

Example 1: The following JavaScript program will illustrate the solution

<script type = “text/javascript” >
// JavaScript program to illustrate
// calculation of no. of days between two date

// To set two dates to two variables
var date1 = new Date(“06/30/2019”);
var date2 = new Date(“07/30/2019”);

// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() – date1.getTime();

// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

//To display the final no. of days (result)
document.write(“Total number of days between dates <br>”
+ date1 + “<br> and <br>”
+ date2 + ” is: <br> ”
+ Difference_In_Days);

</script>

Output

Total number of days between dates 
Sun Jun 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time)
and 
Tue Jul 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time) is: 
30

Tip solutie

Permanent

Voteaza

(9 din 25 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?