如何计算一个人的月龄/年龄,以便两岁以下的人只能在几个月内报告,2年以上的报告只能在几年内报告?
答案 0 :(得分:3)
我会使用NodaTime:
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;
答案 1 :(得分: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");
答案 2 :(得分:0)
我真的输了一个小时+这个挑战,我觉得这很简单。在另一个可能有用的问题上找到了这个答案
答案 3 :(得分:-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";
}