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?
Asked
Active
Viewed 639 times
0
-
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 Answers
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
-
Was this meant to be the code that you've already tried? If so, you should have included it in your question. – jonvuri Nov 13 '12 at 01:24
-
1@Kiyura : Really? Suggest you read the following post: http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ – spender Nov 13 '12 at 01:29
-
@spender, I am quite aware, I just wanted to be sure he wasn't making a mistake. I probably should have taken a gander at his rep first. :) – jonvuri Nov 13 '12 at 01:32
-
-
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
-
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
-
That almost never gives the right answer. Then length of a year is not 365.25, nor is a month 1/12th of a year. – Jonathan Allen Nov 13 '12 at 03:34
-
-