0

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.....

davy
  • 4,474
  • 10
  • 48
  • 71
  • 1
    Just realised that but I suppose my question is - what is wrong with this approach rather than what is right with that one :) – davy Feb 28 '14 at 12:37
  • I've change the question title. – davy Feb 28 '14 at 12:39
  • 1
    One bug is that a bloke who was born more than about 1500 years ago will be reported as one year older, because of the cumulative rounding of ignoring the .25's try `new DateTime(512, 1, 1), new DateTime(2014, 1, 1)` – StuartLC Feb 28 '14 at 12:51

0 Answers0