JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JavaScript – Difference Between Two Dates

April 10, 2014 by Krishna Srinivasan Leave a Comment

Let us see an example on how calculate difference between dates using Javascript. First write a HTML code with Javascript as below:

[code lang=”html”]
<!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>
[/code]

  • 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.

When the execution process is completed successfully we will get the following output:

JavaScript - Difference Between Two Dates

Filed Under: JavaScript Tagged With: JavaScript Tutorials

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved