如何以月/年计算一个人的年龄,以使两岁以下的任何人都以月为单位报告,2 岁以上的人仅以年为单位报告?
问问题
553 次
4 回答
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;
于 2012-11-13T06:59:50.903 回答
0
我已经在这个挑战中浪费了一个多小时,我认为这很简单。在另一个可能有用的 SO 问题上找到了这个答案
于 2012-11-13T02:39:52.833 回答
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");
于 2012-11-13T01:22:39.550 回答
-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";
}
于 2012-11-13T02:30:29.357 回答