TheMaj0r

Hello, I have a datetime the holds a birthdate, for example 5/1/1984, I want to create a method that takes this date and return a string for the age ,for example 23 years and 9 months and 30 days

Thanks

### Re: Visual C# General Math with datetime??

BinaryCoder

These "age" problems are more complex than they appear on the surface.

To just handle the "years" part, consider this method:

Code Block

// Returns the number of complete years (age) between d1 and d2.

public static int CalculateAge(DateTime d1, DateTime d2)

{

int years = d2.Year - d1.Year;

DateTime anniversary = new DateTime(d2.Year, d1.Month, d1.Day) + d1.TimeOfDay;

if (anniversary > d2)

years -= 1; // Check if did not yet reach the anniversary DateTime.

return years;

}

By months and days, you need to define what "months and days" mean: not all months have the same number of days. You could easily adapt the above to find year and days:

int days = (d2 - anniversary).Days;

### Re: Visual C# General Math with datetime??

TheMaj0r

Thanks, The most complex is computing the months and days as we dont know the days of months and how many leap years were within the two dates DateTime dob = DateTime.Parse(TextBox1.Text);

int days = ((TimeSpan)(DateTime.Now - dob)).Days;

int years = (int)(days / 365.25);

int months = (int)(days / 30.4375);

int involvedMonths = years * 12;

int monthsSlack = months - involvedMonths;

int involvedDays = (int)(monthsSlack * 30.4375);

int daysSlack = (int)((days - (years * 365.25)) - involvedDays);

Label1.Text = years.ToString() + "Years, " + monthsSlack.ToString() + "Months, " + daysSlack.ToString() + "Days.";

### Re: Visual C# General Math with datetime??

BinaryCoder

There is no "one" answer to this problem. It is all a matter of how you define "age". You haven't provided a rock solid definition of "age" (which, of course, needs to say what to do about the differences in the number of days per month).

### Re: Visual C# General Math with datetime??

TheMaj0r

I just simplified it and defined average of days per month which is about 30.4

### Re: Visual C# General Math with datetime??

TheMaj0r

Thanks worked accuretly