/ 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.
Expand |
Embed | Plain Text
private static double GetAge(DateTime birthDate, DateTime today) { // get the last birthday int years = today.Year - birthDate.Year; DateTime last = birthDate.AddYears(years); if (last > today) { last = last.AddYears(-1); years--; } // get the next birthday DateTime next = last.AddYears(1); // calculate the number of days between them double yearDays = (next - last).Days; // calcluate the number of days since last birthday double days = (today - last).Days; // calculate exact age double exactAge = (double)years + (days / yearDays); return exactAge; }
You need to login to post a comment.
