Skip to main content Skip to footer

Don't Forget Your Leap Years!

Last night at the Hampton Roads .NET Users Group, I did a small lightning talk on the importance of detecting leap years. If you're developing with .NET and have a use case that would have issues when a leap year was in effect (maybe a billing system or *ahem* certificate renewal system), you'll want to use DateTime.IsLeapYear() to detect whether you're dealing with a leap year.


bool is2011LeapYear = DateTime.IsLeapYear(2011); // false  
bool is2012LeapYear = DateTime.IsLeapYear(2012); // true  

Really this is typically only an issue if you're trying to find the max day of any particular month. If that's the case, don't hard code the values. Use the DateTime.DaysInMonth() method to define them for you.


int daysInFeb2011 = DateTime.DaysInMonth(2011, 2); // 28  
int daysInFeb2012 = DateTime.DaysInMonth(2012, 2); // 29

It only takes one leap year to screw up your app! MSDN Link for IsLeapYear MSDN Link for DaysInMonth

MESCIUS inc.

comments powered by Disqus