Yesterday I was working on something similar, but something like this should fit your needs: (within 7 days, 31 days, 365 days, etc.)
Revised Method: (corrected according to 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!
Rion williams
source share