how to calculate age?

how can i calculate age in years and months.. for example 26y 2m




Answer this question

how to calculate age?

  • bhmsaad

    DateTime birthday = ......

    TimeSpan age = DateTime.Now - birthday;

    int years = age.Days/ 365;
    int months = (age.Days - (year * 365))/30;
    string strAge = String.Format("{0}y {1}m", years, months);



  • bilalso

    What have you tried so far The following might inspire you...


    public static long TimeSpan(DateTime begin, DateTime end, SpanUnit spanUnit)
    {
    TimeSpan ts = ts = end - begin;

    switch (spanUnit)
    {
    case SpanUnit.Year:
    return end.Year - begin.Year;
    case SpanUnit.Month:
    return (end.Month - begin.Month) + (12 * (end.Year - begin.Year));
    case SpanUnit.Weekday:
    return Fix(ts.TotalDays) / 7;
    case SpanUnit.Day:
    return Fix(ts.TotalDays);
    case SpanUnit.Hour:
    return Fix(ts.TotalHours);
    case SpanUnit.Minute:
    return Fix(ts.TotalMinutes);
    default:
    return Fix(ts.TotalSeconds);
    }
    }

    private static long Fix(double number)
    {
    if (number >= 0)
    {
    return (long)Math.Floor(number);
    }
    return (long)Math.Ceiling(number);
    }

    public enum SpanUnit
    {
    Year,
    Month,
    Weekday,
    Day,
    Hour,
    Minute,
    Second
    }


  • how to calculate age?