Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate an age from a DateTime in Years.Months format?

Tags:

c#

algorithm

Does anyone have an algorithm in c# to accurately calculate an age given a DateTime in the format Years.Months?

eg.

  • DOB: 6-Sep-1988
  • Answer: 23.4

  • DOB: 31-Mar-1991

  • Answer: 20.10

  • DOB: 25-Feb-1991

  • Answer: 20.11

thanks

like image 523
gregpakes Avatar asked Feb 03 '12 11:02

gregpakes


2 Answers

You can do this in Noda Time fairly easily:

using System;
using NodaTime;

class Test
{
    static void Main()
    {
        ShowAge(1988, 9, 6);
        ShowAge(1991, 3, 31);
        ShowAge(1991, 2, 25);
    }

    private static readonly PeriodType YearMonth =
        PeriodType.YearMonthDay.WithDaysRemoved();

    static void ShowAge(int year, int month, int day)
    {
        var birthday = new LocalDate(year, month, day);
        // For consistency for future readers :)
        var today = new LocalDate(2012, 2, 3);

        Period period = Period.Between(birthday, today, YearMonth);
        Console.WriteLine("Birthday: {0}; Age: {1} years, {2} months",
                          birthday, period.Years, period.Months);
    }
}

Doing it with just .NET's DateTime support would be possible, but you'd have to do the arithmetic yourself, basically. And it almost certainly wouldn't be as clear. Not that I'm biased or anything :)

like image 129
Jon Skeet Avatar answered Oct 21 '22 11:10

Jon Skeet


This method doesn't require any external libraries:

private static string AgeInYearsMonths(DateTime? DateOfBirth)
{
    if (DateOfBirth == null) return "";
    if (DateOfBirth >= DateTime.Today)
        throw new ArgumentException("DateOfBirth cannot be in future!");

    DateTime d = DateOfBirth.Value;
    int monthCount = 0;
    while ((d = d.AddMonths(1)) <= DateTime.Today)
    {
        monthCount++;
    }
    return string.Format("{0}.{1}", monthCount / 12, monthCount % 12);
}
like image 20
benrwb Avatar answered Oct 21 '22 12:10

benrwb