[英]How do I calculate a person's age in months/years?
我如何計算一個人的月齡/年齡,這樣兩歲以下的人只能在幾個月內報告,2年以上的報告只能在幾年內報告?
我會使用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;
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");
我真的輸了一個小時+這個挑戰,我覺得這很簡單。 在另一個可能有用的SO問題上找到了這個答案
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.