JavaScript Date Difference

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

<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")

Output will be displayed as:

Download Source Code: