I am working on some medical software and I am required to output all ages in a very specific manner, based on the following rules:
If under 6 Weeks old :
I was working on something similar yesterday, but something like this should suit your needs: (assuming 7 day weeks, 31 day months, 365 day years etc.)
Revised Method : (Fixed as per Bob's suggestions)
public static string ConvertAge(DateTime dob)
{
DateTime today = DateTime.Today;
string fmt = "{0:0##}{1}";
//Greater than 2 Years old - Ouput Years
if (dob <= today.AddYears(-2))
return string.Format(fmt, (dob.DayOfYear <= today.DayOfYear) ?
(today.Year - dob.Year) : (today.Year - dob.Year)-1, "Y");
//Less than 2 Years - Output Months
if (dob < today.AddMonths(-2))
return string.Format(fmt, (dob.DayOfYear <= today.DayOfYear) ?
(today.Year - dob.Year) * 12 + (today.Month - dob.Month) :
((today.Year - dob.Year) * 12 + (today.Month - dob.Month))-1 , "M");
//Less than 2 Months - Output Weeks
if (dob < today.AddDays(-2 * 7))
return string.Format(fmt, (today - dob).Days / 7, "W");
//Less than 2 Weeks - Output Days
return string.Format(fmt, (today - dob).Days, "D");
}
Previous Method :
public string ConvertAge(DateTime dateOfBirth)
{
int daysOld = (DateTime.Now - dateOfBirth).Days;
//Age < 6 Weeks
if (daysOld < (6 * 7))
return String.Format("{0:0##}{1}", daysOld, 'D');
//Age < 6 Months
else if (daysOld < (6 * 31))
return String.Format("{0:0##}{1}", daysOld/7, 'W');
//Age < 2 Years
else if (daysOld < (2 * 365))
return String.Format("{0:0##}{1}", daysOld / 31, 'M');
//Age >= 2 Years
else
return String.Format("{0:0##}{1}", daysOld / 365, 'Y');
}
Hope this helps!