Let us see an example on how calculate difference between dates using Javascript. First write a HTML code with Javascript as below:
<!DOCTYPE html> <body> <script type="text/javascript"> var d1 = new Date("12/12/2013"); var d2 = new Date("12/12/2014"); var timeDiff = d2.getTime() - d1.getTime(); var DaysDiff = timeDiff / (1000 * 3600 * 24); document.write("Days of difference between <br>"+d1+"<br> and <br>"+d2+" is:<br> " +DaysDiff); </script> </body> </html>
- The above program is used to calculate the days of difference between two dates .
- we have set two dates to two variables in the program var d1 = new Date(“12/12/2011”); and
var d2 = new Date(“12/12/2014”); and then we have calculated the difference of days between
these two dates. - var timeDiff = d2.getTime() – d1.getTime(); is used to calculate the time difference
of the date. - var DaysDiff = timeDiff / (1000 * 3600 * 24); is used to calculate the difference
between the two days by dividing the time difference value with (1000 * 3600 * 24) i.e.
1000 millisecond , 3600 minutes and 24 hours. - document.write(“Days of difference is:” +DaysDiff); is used to display the days.
JavaScript Difference Between Two Dates Demo
- Save the file as date_diff.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.