tags:

views:

159

answers:

7

Hello guys, anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();

and the output will be some thing like 20Years 5Months 20Days

+3  A: 

See the answers at How do I calculate someone’s age in C#? for ideas.

Jonathan S.
A: 

To get the age I would use the datetime of the birthdate and find the difference between that and the current system time. This link shows how to find the difference between two datetimes. Just make the starttime be the user's birthdate and endtime be now (DateTime.Now;)

Kyra
+3  A: 

This sounds like a fine exercise to get to know the TimeSpan class better.

thomask
+1  A: 

But please, if you intend to generate some english out of it, take care of singular and plural in corner cases, to avoid "1 years 3 months 1 days". Luckily, you only need to append an 's' in English.

Arne
+1  A: 

Not certain that it would always be correct (haven't thought about if there's some cases with leap years etc that might make it fail...), but this is an easy way to get out the year and month:

DateTime bd = DateTime.Parse("2009-06-17");
TimeSpan ts = DateTime.Now.Subtract(bd);
DateTime age = DateTime.MinValue + ts;
string s = string.Format("{0} Years {1} months {2} days", age.Year -1 , age.Month - 1, age.Day - 1);
ho1
That can definitely be incorrect. DateTime.MinValue + ts` probably has a different number of days (leap years, etc.) than the actual date range we're dealing with.
Nelson
@Nelson: Not sure though, if you use `1970-06-16` as the bd it returns 40 years exactly, which is correct, and that date range spans quite a few leap years.
ho1
@ho1 - But do `1900-06-16` and now you have +1 day. It's very close, but not exact.
Nelson
@ho1 - In this specific case, it seems to be incorrect once you get over 100 years. I'm not sure if there are other problems or not. This may be close enough and not worth any extra effort.
Nelson
A: 
public static class DateTimeExtensions
{
    public static string ToAgeString(this DateTime dob)
    {
        DateTime dt = DateTime.Now;

        int days = dt.Day - dob.Day;
        if (days < 0)
        {
            dt = dt.AddMonths(-1);
            days += DateTime.DaysInMonth(dt.Year, dt.Month);
        }

        int months = dt.Month - dob.Month;
        if (months < 0)
        {
            dt = dt.AddYears(-1);
            months += 12;
        }

        int years = dt.Year - dob.Year;

        return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                             years, (years == 1) ? "" : "s",
                             months, (months == 1) ? "" : "s",
                             days, (days == 1) ? "" : "s");
    }
}
LukeH