你好所以我实现了这个解决方案,从一个生日日期输入获得用户的生日: 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