Return Age from Date of Birth


/ Published in: JavaScript
Save to your folder(s)

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")


Copy this code and paste it in your HTML
  1. /**
  2.  * Calculate Age
  3.  *
  4.  * Calculates the amount of time since the date specified with yr, mon, and day.
  5.  * The parameter "countunit" can be "years", "months", or "days" and is the duration
  6.  * between the specified day and today in the selected denomination. The "decimals"
  7.  * parameter allows you to set a decimal place to round to for days and months return
  8.  * values. Rounding is also meant for days and months and can be "roundup" or "rounddown"
  9.  * based solely on the properties of Math.ceil and math.floor respectively.
  10.  * Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
  11.  */
  12. function displayage( yr, mon, day, countunit, decimals, rounding ) {
  13.  
  14. // Starter Variables
  15. today = new Date();
  16. yr = parseInt(yr);
  17. mon = parseInt(mon);
  18. day = parseInt(day);
  19. var one_day = 1000*60*60*24;
  20. var one_month = 1000*60*60*24*30;
  21. var one_year = 1000*60*60*24*30*12;
  22. var pastdate = new Date(yr, mon-1, day);
  23. var return_value = 0;
  24.  
  25. finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year;
  26. decimals = ( decimals <= 0 ) ? 1 : decimals * 10;
  27.  
  28. if ( countunit != "years" ) {
  29. if ( rounding == "rounddown" )
  30. return_value = Math.floor ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
  31. else
  32. return_value = Math.ceil ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
  33. } else {
  34. yearspast = today.getFullYear()-yr-1;
  35. tail = ( today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day ) ? 1 : 0;
  36. return_value = yearspast + tail;
  37. }
  38.  
  39. return return_value;
  40.  
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.