0

How do I calculate a person's age in months/years such that anyone under two years old is reported in months and 2+ years in years only?

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • Yeah, I thought this looked trivial but it's surprisingly not as straight forward as you would expect. – Brad Nov 13 '12 at 02:55
  • @JohanLarsson, that doesn't answer the question of months. And if you read the comments, you see that the #1 answer isn't even right for just years. – Jonathan Allen Nov 13 '12 at 03:29

4 Answers4

3

I would use NodaTime for this:

var d1 = new NodaTime.LocalDate(1997, 12, 10);
var d2 = new NodaTime.LocalDate(2012, 11, 13);

var period = NodaTime.Period.Between(d1, d2);
var m = period.Months;
var y = period.Years;
L.B
  • 114,136
  • 19
  • 178
  • 224
0
var now = DateTime.Today;

int months = 0;
while (true)
{
    var temp = dob.AddMonths((int)months);
    if (now < temp)
    {
        if (now.Day < temp.Day)
            months--; //accounts for short months
        break;
    }
    months++;
}

if (months < 24)
    return (months + " months");
else
    return (Math.Floor( (decimal)months / 12.0M) + " years");
jonvuri
  • 5,738
  • 3
  • 24
  • 32
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
0

I've literally lost an hour+ to this challenge, I thought it would be simple. Have found this answer on another SO question which may be useful

C# Formatting Age - Regarding Days, Weeks , Months - Years

Community
  • 1
  • 1
NoPyGod
  • 4,905
  • 3
  • 44
  • 72
  • That works for the US, but not for other countries. "Several countries have skipped dates after the birth of current living people, including Russia (1918), Greece (1924) and Turkey (1926)." – Lars D Nov 9 '09 – Jonathan Allen Nov 13 '12 at 03:30
  • Yeah it's a complicated problem, you may wish to find a library to do it for you if it's very important to have accurate figures. – NoPyGod Nov 13 '12 at 03:32
-1
private string Birthdate(DateTime birthday)
{
    var birthdayTicks = birthday.Ticks;
    var twoYearsTicks = birthday.AddYears(2).Ticks;
    var NowTicks = DateTime.Now.Ticks;

    var moreThanTwoYearsOld = twoYearsTicks < NowTicks;

    var age = new DateTime(DateTime.Now.Subtract(birthday).Ticks);

    return moreThanTwoYearsOld ? (age.Year-1).ToString() + " years" : (age.Year-1 >= 1 ? age.Month + 12 : age.Month).ToString() + " months";
}
Brad
  • 11,934
  • 4
  • 45
  • 73