Reputation: 70337
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?
Upvotes: 1
Views: 736
Reputation: 12253
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";
}
Upvotes: -1
Reputation: 116178
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;
Upvotes: 5
Reputation: 5067
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
Upvotes: 0
Reputation: 70337
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");
Upvotes: 0