Wednesday, May 16, 2012

How would you calculate the age in C# using date of birth (considering leap years)

Here is a problem. I have seen many solutions, but no one seems to be fulfilling the criteria I want...



I want to display the age in this format



20 y(s) 2 m(s) 20 d(s)
20 y(s) 2 m(s)
2 m(s) 20 d(s)
20 d(s)


etc...



I have tried several solutions, but the leap year is causing the problem with me. My unit tests are always being failed because of leap years and no matter how many days come in between, the leap yeas count for extra number of days.



Here is my code....



public static string AgeDiscription(DateTime dateOfBirth)
{
var today = DateTime.Now;
var days = GetNumberofDaysUptoNow(dateOfBirth);
var months = 0;
var years = 0;
if (days > 365)
{
years = today.Year - dateOfBirth.Year;
days = days % 365;
}
if (days > DateTime.DaysInMonth(today.Year, today.Month))
{
months = Math.Abs(today.Month - dateOfBirth.Month);
for (int i = 0; i < months; i++)
{
days -= DateTime.DaysInMonth(today.Year, today.AddMonths(0 - i).Month);
}
}

var ageDescription = new StringBuilder("");

if (years.ToString() != "0")
ageDescription = ageDescription.Append(years + " y(s) ");
if (months.ToString() != "0")
ageDescription = ageDescription.Append(months + " m(s) ");
if (days.ToString() != "0")
ageDescription = ageDescription.Append(days + " d(s) ");

return ageDescription.ToString();
}

public static int GetNumberofDaysUptoNow(DateTime dateOfBirth)
{
var today = DateTime.Now;
var timeSpan = today - dateOfBirth;
var nDays = timeSpan.Days;
return nDays;
}


Any ideas???





No comments:

Post a Comment