你好所以我實現了這個解決方案,從一個生日日期輸入獲得用戶的生日: Calculate age in C#生日年齡計算,而且數月的天數
這個偉大的工程,但是我確實需要解釋的生日的年齡不到一年(嬰兒,嬰兒)。如果當天和當前日期之間的時間少於365天,它現在只會給我一個「0」的年齡。
我在想什麼是這樣的:
public string calculateAge(DateTime birthDate, DateTime now)
{
//BDay is in different year (age > 1)
int age = now.Year - birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
if (age == 0)
{
//Bday is in same year
age = now.Month - birthDate.Month;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
return age.ToString() + " months";
}
if (age == 0)
{
//Bday is in the same month
age = now.Day - birthDate.Day;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
return age.ToString() + " days";
}
return age.ToString();
}
但是我的一些測試Bdays的給我這個:
(Today's date: 3/6/2012)
Bday1 = 3/5/2012
Age result = -1
Expected result = 1 day
Bday2 = 3/1/2012
Age result = 0 months
Expected result = 5 days
Bday3 = 1/1/2012
Age result = 2 months
Expected result = 2 months (this is fine)
Bday4 = 3/7/2011
Age result = -1 months
Expected result = 11 months
Bday5 = 3/1/2011
Age result = 1
Expected result = 1 (this is fine)
你可以看到,因爲它是目前設置瞭如何問題源於bday月份小於當前月份的某些負數可能導致的結果。
我也看到關於不能進入「天」循環的錯誤,但我認爲這是一個毫無意義的問題。如果您對我可以做些什麼以獲得理想的結果有所瞭解,請告訴我。另外如果你需要更多的信息,比如測試bdays。謝謝!
上面並沒有考慮到 「天」。但是,將它留在這裏爲後代無論如何... – Reddog 2012-03-07 01:59:35