Calculate the difference between two dates in JavaScript

Use the Date object to calculate, determine the deviation in years or days, and get the age of a person.

Difference between two dates in years

Here is the JavaScript function that performs the calculation. As an argument, she refers to the last two dates. There is a simpler code that we will give, but it gives access to more information about 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 ("March 31, 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 = datenew - dateold;
  if(mold > mnew) diff--;
  else
  {
    if(mold == mnew)
    {
      if(dold > dnew) diff--;
    }
  }
  return diff;
}

Demonstration:

Demo Code...

var today = new Date();
var olday = new Date("1 January 2000");
document.write("Années depuis le 1 janvier 2000: ");
document.write(dateDiff(olday, today));
document.write(" ans.");

Difference in days

To do this, we will translate years into days, the difference is easier.

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

Demonstration:

Year differences, simpler code

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

Code:

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

Demonstration:

Calculate the age of a person

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

Code:

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

Demonstration:

Michael Schumacher age - years.

Code:

L'âge de Michael Schumacher est de 
<script>document.write(age("3 January 1969"))</script> ans.

Live demonstration