How to calculate the difference between two dates in JavaScript

By using the Date object to make calculations, we define a difference in years or days, and obtain a person's age

Difference between two dates in years

Here is a JavaScript function that performs the calculation. It takes two dates and the second argument is the later. There is a simpler code that we will give, but this one provides access to more information about the dates.

For example, the age of the Eiffel Tower is years, a number that is calculated using the following formula: new Number((new Date().getTime() - new Date("31 March 1889").getTime()) / 31536000000).toFixed(0).

function dateDiff(dateold, datenew)
{
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var dnew = datenew.getDate();
var yold = dateold.getFullYear();
var mold = dateold.getMonth();
var dold = dateold.getDate();
var diff = ynew - yold;
if(mold > mnew) diff--;
else
{
if(mold == mnew)
{
if(dold > dnew) diff--;
}
}
return diff;
}

Demonstration:

Code of the demonstration...

var today = new Date();
var olday = new Date("1 January 2000");
document.write("Years since January 1, 2000: ");
document.write(dateDiff(olday, today));
document.write(" years.");

Difference in days

For this case we convert years to days, the difference is simple.

function dayDiff(d1, d2)
{
  d1 = d1.getTime() / 86400000;
  d2 = d2.getTime() / 86400000;
  return new Number(d2 - d1).toFixed(0);
}

Demonstration:

Differences in years, simpler code

We use the previous code for the difference in days and divide by 365.

The code:

function dayDiff(d1, d2)
{
  return new Number((d2.getTime() - d1.getTime()) / 31536000000).toFixed(0);
}

Demonstration:

Calculating the age of a person

To view the age of a person or thing, the previous code is used again, with date of birth as the first parameter, but without a second parameter.

The code:

function age(birthday)
{
  birthday = new Date(birthday);
  return new Number((new Date().getTime() - birthday.getTime()) / 31536000000).toFixed(0);
}

Demonstration:

The age of Michael Schumacher is years.

Code:

The age of Michael Schumacher is 
<script>document.write(age("3 January 1969"))</script> 
years.

Live demonstration