Home Javascript Javascriptexamples JavaScript Date Difference
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

JavaScript Date Difference

Advertisement
This page discusses - JavaScript Date Difference

JavaScript Date Difference

        

In this section, we are going to determine the difference between two dates.

As you have already learnt about the JavaScript method Date.getTime() that returns the time (in milliseconds) elapsed from 1st January, 1970 to the current Date instance. In the given example, firstly we have created two instances of Date to set two dates i.e current date and the date specified. Then we have used this method in order to get the number of days between two dates. 

getFullYear()-This method return the  current year.
Math.ceil()
- This method returns the rounded number to the nearest integer.

Following code calculate the difference between two dates in days:

Math.ceil((date.getTime()-today.getTime())/(day))+" days")

Here is the code:

<html>
<h2>Date Difference</h2>
<script type="text/javascript">
var today=new Date()
var date=new Date(today.getFullYear(), 2, 11) 
var day=1000*60*60*24;
document.write("Today's date is :"+today+"<br>");
document.write("Another date is :"+date+"<br>");
document.write("Difference between two dates is :"+
  Math.ceil((date.getTime()-today.getTime())/(day))+" days")
</script>
</html>

Output will be displayed as:

Download Source Code:

        

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Ask Questions?    Discuss: JavaScript Date Difference  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
tiru
January 5, 2012
code

gooed
tiru
January 5, 2012
datecode

GOOD
Bhavesh Chhatbar
July 13, 2012
Thanks

Thank you so much! I was looking for reverse of this, but your note helped :)
DMCA.com