OK, rather than mess with the existing script to correct for leap years, and since its months calculation was also faulty because not all months have 30 days, I decided to start from scratch and use the date object itself to keep things accurate. Let me know if you have any problems or questions:
Code:
<!DOCTYPE html>
<html>
<head>
<title>How Old - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
// howold Script (c)2017 John Davenport Scheuer
// as first seen in http://www.dynamicdrive.com/forums/
// username: jscheuer1 - This Notice Must Remain for Legal Use
function howold(pastdate, units, round, id){
if(isNaN(new Date(pastdate))){return document.getElementById(id).innerHTML = 'Invalid Date';}
var pd = new Date(pastdate), now = new Date(), cf = round === 'down'? 'floor' : round === 'round'? round : 'ceil',
pdm = (function(){var p = new Date(pastdate); p.setFullYear(now.getFullYear()); return p.getMonth();})(), wu = units.toLowerCase(),
yrs = now.getFullYear() - pd.getFullYear(), mos = now.getMonth() - pdm, samemonth = now.getMonth() === pd.getMonth(), r, ru;
if(round === 'down'){
if(wu === 'months' && now.getDate() < pd.getDate()){--mos;}
if(wu === 'years' && (mos < 0 || (samemonth && now.getDate() < pd.getDate()))){--yrs;}
}
if(wu === 'years'){r = yrs;}
else if(wu === 'months'){r = yrs * 12 + mos;}
else if(wu === 'days'){r = Math[cf]((now.getTime() - pd.getTime()) / (1000 * 60 * 60 * 24));}
else {r = 'Invalid Units'; units = ''};
ru = r === 1? units.replace('s', '') : units;
document.getElementById(id).innerHTML = r + ' ' + ru;
}
</script>
</head>
<body>
<div>April 30 2017 was <span id="a30"></span> Ago.</div>
<div>Bill Gates is <span id="bill"></span> Old.</div>
<div>March 15th, 2017 was <span id="dayexample"></span> ago.</div>
<script>
/* Usage (note - Units are case insensitive. The round parameter may be set to 'round' if the units are days):
howold(pastdate[valid date format], units['years', 'months', 'days'], round['up', 'down'], id['id_of_element' to write to]);
Typical Outputs (units returned as entered, made singular if the number is one):
1 Month
61 Years
72 days
*/
howold('April, 30, 2017', 'Months', 'up', 'a30');
howold('Oct, 28, 1955', 'Years', 'down', 'bill');
howold('Mar, 15, 2017', 'days', 'round', 'dayexample');
</script>
</body>
</html>
Bookmarks