为什么我不应该用这种方法来计算英国的当地年龄?

时间:2014-02-28 12:33:31

标签: c# datetime

我写了以下代码来确定某人是否在英国是18岁。如果这个人是'leapling'(2月29日出生),我希望它可以解决。

int age;
if (DateTime.IsLeapYear(startDate.Year) && startDate.Month == 2 && startDate.Day == 29)
{
   age = (int)Math.Floor((endDate - startDate).TotalDays / 365.25);
}
else
{
   age = (int)Math.Floor((endDate - startDate).TotalDays / 365);
}
return age;

我已经使用各种日期对其进行了大致测试(例如,仅为演示目的的可怕代码的apologo):

DateTime startDateLeapYearNonLeapling = new DateTime(1996, 02, 28, 0 , 0, 0, 0, DateTimeKind.Local);
DateTime endDateLeapYearNonLeapling = new DateTime(2014, 02, 28, 0, 0, 0, 0, DateTimeKind.Local);

DateTime startDateLeapling = new DateTime(1996, 02, 29, 0 , 0, 0, 0, DateTimeKind.Local);
DateTime endDateLeaplingToday28Feb = new DateTime(2014, 02, 28, 0 , 0, 0, 0, DateTimeKind.Local);
DateTime endDateLeaplingToday1March = new DateTime(2014, 03, 01, 0 , 0, 0, 0, DateTimeKind.Local);   

DateTime startDateNonLeapYear = new DateTime(1996, 03, 28, 0 , 0, 0, 0, DateTimeKind.Local);
DateTime endDateNonLeapYear = new DateTime(2014, 03, 28, 0 , 0, 0, 0, DateTimeKind.Local);

int ageLeapYearNoLeapling = GetAge(startDateLeapYearNonLeapling, endDateLeapYearNonLeapling);   //18
int ageLeapYearLeaplingToday28Feb = GetAge(startDateLeapling, endDateLeaplingToday28Feb);       //17
int ageLeapYearLeaplingToday1Marach = GetAge(startDateLeapling, endDateLeaplingToday1March);    //18
int ageNonLeapYear = GetAge(startDateNonLeapYear, endDateNonLeapYear);   //18                       

在正确的测试用例中返回18和17。

代码似乎有效,但我知道DateTime计算可能会让我们失望。

我有没有错过的案例?

我也对一个更优雅的解决方案感兴趣,如果有人有一个甚至如何让这个工作与不同的文化,但这可能是另一天.....

0 个答案:

没有答案