要知道如何計算年齡,包含年、月、日?
有朋友想要知道如何計算年齡,包含年、月、日。
網路上有人分享出來(How to calculate an age based on a birthday?),只是Code似乎有點問題,所以將它修改一下,如下,
public struct Age
{
public int Years;
public int Months;
public int Days;
}
public static Age CalculateAge(DateTime birthDate, DateTime endDate)
{
if (birthDate.Date > endDate.Date)
{
throw new ArgumentException("birthDate cannot be higher then endDate", "birthDate");
}
int years = endDate.Year - birthDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if (endDate < birthDate.AddYears(years) && years != 0)
{
years--;
}
// Calculate the number of months.
birthDate = birthDate.AddYears(years);
if (birthDate.Year == endDate.Year)
{
months = endDate.Month - birthDate.Month;
}
else
{
months = (12 - birthDate.Month) + endDate.Month;
}
// Check if last month was a complete month.
if (endDate < birthDate.AddMonths(months) && months != 0)
{
months--;
}
// Calculate the number of days.
birthDate = birthDate.AddMonths(months);
days = (endDate - birthDate).Days;
Age result;
result.Years = years;
result.Months = months;
result.Days = days;
return result;
}
測試方式如下,
DateTime myBirthday = DateTime.ParseExact("1974/03/08", "yyyy/MM/dd", null);
DateTime flakNow = DateTime.ParseExact("2013/03/08", "yyyy/MM/dd", null);
Age myAge = CalculateAge(myBirthday, flakNow);
參考資料
How to calculate an age based on a birthday?
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^