JSFiddle - React, Tailwind, and code Playground
by spechackers
JavaScript
function getAge(fromdate,currentDate){
var currentDate= new Date(currentDate);
var age= [], fromdate= new Date(fromdate),
y= [currentDate.getFullYear(), fromdate.getFullYear()],
ydiff= y[0]-y[1],
m= [currentDate.getMonth(), fromdate.getMonth()],
mdiff= m[0]-m[1],
d= [currentDate.getDate(), fromdate.getDate()],
ddiff= d[0]-d[1];
if(mdiff < 0 || (mdiff=== 0 && ddiff<0))--ydiff;
if(mdiff<0) mdiff+= 11;
if(ddiff<0){
fromdate.setMonth(m[1]+1, 0);
ddiff= fromdate.getDate()-d[1]+d[0];
--mdiff;
}
if(ydiff> 0) age.push(ydiff+ 'Y');
if(mdiff> 0) age.push(mdiff+ 'M');
if(ddiff> 0) age.push(ddiff+ 'D');
if(age.length>1) age.splice(age.length-1,0);
alert(age);
}
//getAge("01/01/2011")
getAge(new Date(), "12/25/2011")