Posted By

jatkins on 04/27/11


Tagged

AGE CALCULATION Calculator


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

catrinho


Calculate Age


 / Published in: JavaScript
 

Released into the public domain. This shouldn't be remotely relevant, but obviously this will not work BC years. Dates passed to the two params should be strings in the format YYYY-MM-DD. Bugs fixed in 1/7/2012 version.

  1. function calculateAgeInYears(originalDate, dateToCalculateAgeOn) {
  2. if(!(typeof dateToCalculateAgeOn != 'undefined' && dateToCalculateAgeOn)) {
  3. dateToday = new Date();
  4. dateToCalculateAgeOn = dateToday.getFullYear() + '-' + (dateToday.getMonth() + 1) + '-' + dateToday.getDate();
  5. }
  6. originalDate = originalDate.replace(/[^0-9\-]/g, '').split('-');
  7. dateToCalculateAgeOn = dateToCalculateAgeOn.replace(/[^0-9\-]/g, '').split('-');
  8. for(var y=0;y<=2;y++) {
  9. originalDate[y] = parseInt(originalDate[y]);
  10. dateToCalculateAgeOn[y] = parseInt(dateToCalculateAgeOn[y]);
  11. }
  12. if(dateToCalculateAgeOn[0]>originalDate[0]) {
  13. ageDetermined = (dateToCalculateAgeOn[0] - originalDate[0]) - 1;
  14. if(((dateToCalculateAgeOn[1]==originalDate[1])&&(dateToCalculateAgeOn[2]>=originalDate[2]))||(dateToCalculateAgeOn[1]>originalDate[1]))
  15. return ageDetermined + 1; // returns age in years
  16. else
  17. return ageDetermined;
  18. }
  19. else
  20. return originalDate[0]==dateToCalculateAgeOn[0] ? 0 : false;
  21. return false;
  22. }

Report this snippet  

You need to login to post a comment.