Verification: a143cc29221c9be0

New date gettime в php 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: