I have written the following code to determine if someone is 18 in the UK. I want it to work out if the person was a 'leapling
' (born on 29 February).
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;
I have roughly tested it using the various dates like (apologoes for the horrible code for demo purposes only):
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
Returns 18 and 17 in the correct test cases.
The code appears to work but I know that DateTime
calculations can trip us up.
Are there any cases I have missed?
I'd also be interested in a more elegant solution if anyone has one or even how to make this work with different cultures but that is probably for another day.....