Home Javascript Javascriptexamples JavaScript Date Difference



JavaScript Date Difference
Posted on: April 18, 2011 at 12:00 AM
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:

        

Related Tags for JavaScript Date Difference:


More Tutorials from this section

Ask Questions?    Discuss: JavaScript Date Difference  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.