/ Published in: JavaScript
Calculates the amount of time since the date specified with yr, mon, and day. The parameter "countunit" can be "years", "months", or "days" and is the duration between the specified day and today in the selected denomination. The "decimals" parameter allows you to set a decimal place to round to for days and months return values. Rounding is also meant for days and months and can be "roundup" or "rounddown" based solely on the properties of Math.ceil and math.floor respectively.
Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Calculate Age * * Calculates the amount of time since the date specified with yr, mon, and day. * The parameter "countunit" can be "years", "months", or "days" and is the duration * between the specified day and today in the selected denomination. The "decimals" * parameter allows you to set a decimal place to round to for days and months return * values. Rounding is also meant for days and months and can be "roundup" or "rounddown" * based solely on the properties of Math.ceil and math.floor respectively. * Sample - displayage(1997, 11, 24, "years", 0, "rounddown") */ function displayage( yr, mon, day, countunit, decimals, rounding ) { // Starter Variables today = new Date(); yr = parseInt(yr); mon = parseInt(mon); day = parseInt(day); var one_day = 1000*60*60*24; var one_month = 1000*60*60*24*30; var one_year = 1000*60*60*24*30*12; var pastdate = new Date(yr, mon-1, day); var return_value = 0; finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year; decimals = ( decimals <= 0 ) ? 1 : decimals * 10; if ( countunit != "years" ) { if ( rounding == "rounddown" ) return_value = Math.floor ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals; else return_value = Math.ceil ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals; } else { yearspast = today.getFullYear()-yr-1; tail = ( today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day ) ? 1 : 0; return_value = yearspast + tail; } return return_value; }