Created
November 15, 2012 18:01
-
-
Save stevenwoodson/4080143 to your computer and use it in GitHub Desktop.
Find Age from Month/Day/Year
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function displayage( yr, mon, day, unit, decimal, round ) { | |
| //Sample usage | |
| //displayage (year, month, day, unit, decimals, rounding) | |
| //Unit can be "years", "months", or "days" | |
| //Decimals specifies demical places to round to (ie: 2) | |
| //Rounding can be "roundup" or "rounddown" | |
| //displayage(1997, 11, 24, "years", 0, "rounddown") | |
| today = new Date(); | |
| yr = parseInt(yr, 10); | |
| mon = parseInt(mon, 10); | |
| day = parseInt(day, 10); | |
| 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 countunit = unit; | |
| var decimals = decimal; | |
| var rounding = round; | |
| var return_value = 0; | |
| finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year; | |
| decimals = ( decimals <= 0 ) ? 1 : decimals * 10; | |
| if ( unit != "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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment