Posted By

calebt on 08/19/09


Tagged

AGE


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Fractional Age


 / Published in: C#
 

Calculates fractional age and takes leap years into accounts. I've seen a lot of calculations that divide the total number of days old someone is by 365.25. This fails if the person is born on a leap year and today is not a leap year as it would return a fractional value less than a whole number.

  1. private static double GetAge(DateTime birthDate, DateTime today)
  2. {
  3. // get the last birthday
  4. int years = today.Year - birthDate.Year;
  5. DateTime last = birthDate.AddYears(years);
  6. if (last > today)
  7. {
  8. last = last.AddYears(-1);
  9. years--;
  10. }
  11. // get the next birthday
  12. DateTime next = last.AddYears(1);
  13. // calculate the number of days between them
  14. double yearDays = (next - last).Days;
  15. // calcluate the number of days since last birthday
  16. double days = (today - last).Days;
  17. // calculate exact age
  18. double exactAge = (double)years + (days / yearDays);
  19. return exactAge;
  20. }

Report this snippet  

You need to login to post a comment.