Leon Meijer's Weblog

About my personal life, technology and business/work related...
posts - 128, comments - 334, trackbacks - 0

How to calculate a leap year in C#

It's February 29, 2008 today, a leap day because 2008 is a leap year (instead of a common year). The pseudocode to determine whether a year is a leap year or not:

if (year modulo 4 is 0) and ((year modulo 100 is not 0) or (year modulo 400 is 0)) then leap else no_leap

I was about to write some code in C# with the same functionality when I discovered that this is out-of-the box functionality available in the .NET Framework. Just call the System.DateTime.IsLeapYear(int year) method.

But anyway, here is the C#:

   1: public static bool IsLeapYear(int year) 
   2: { 
   3:     if (year % 4 != 0) 
   4:     { 
   5:         return false; 
   6:     } 
   7:     if (year % 100 == 0) 
   8:     { 
   9:         return (year % 400 == 0); 
  10:     } 
  11:     return true; 
  12: }

Print | posted on Friday, February 29, 2008 1:24 PM |

Powered by: