Convert number of days into years, months, days
You have a bug in your calculation :
it's 0 month.
And if you mean d/m/y then
1 year, 1 month, and 0 day old.
you said between the two dates ( not include) - look here
Anyway here is the right code which include actually count each month - how many days it has ! ( leap year consideration):
notice :
I instantiated it as d/m/yyy. feel free to send right pattern in :
alert(getAge( new Date(2014,0,1),new Date(2015,0,2)))
function getAge(date_1, date_2)
{
//convert to UTC
var date2_UTC = new Date(Date.UTC(date_2.getUTCFullYear(), date_2.getUTCMonth(), date_2.getUTCDate()));
var date1_UTC = new Date(Date.UTC(date_1.getUTCFullYear(), date_1.getUTCMonth(), date_1.getUTCDate()));
var yAppendix, mAppendix, dAppendix;
//--------------------------------------------------------------
var days = date2_UTC.getDate() - date1_UTC.getDate();
if (days < 0)
{
date2_UTC.setMonth(date2_UTC.getMonth() - 1);
days += DaysInMonth(date2_UTC);
}
//--------------------------------------------------------------
var months = date2_UTC.getMonth() - date1_UTC.getMonth();
if (months < 0)
{
date2_UTC.setFullYear(date2_UTC.getFullYear() - 1);
months += 12;
}
//--------------------------------------------------------------
var years = date2_UTC.getFullYear() - date1_UTC.getFullYear();
if (years > 1) yAppendix = " years";
else yAppendix = " year";
if (months > 1) mAppendix = " months";
else mAppendix = " month";
if (days > 1) dAppendix = " days";
else dAppendix = " day";
return years + yAppendix + ", " + months + mAppendix + ", and " + days + dAppendix + " old.";
}
function DaysInMonth(date2_UTC)
{
var monthStart = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth(), 1);
var monthEnd = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
return monthLength;
}
alert(getAge(new Date(2014, 0, 1), new Date(2015, 1, 1)))