July 23, 2009

Get LeapYear using C#

Someone asked me yesterday how to figure out if is a leap year in c# code. It is actually not that complicated and here is how you would do it:
public static bool IsLeapYear(DateTime date)
{
int year = date.Year;

if (year % 400 == 0)
return true;
else if (year % 100 == 0)
return false;
else if (year % 4 == 0)
return true;
else
return false;
}
Check for it this way:
public static int DaysInYear(DateTime date)
{
return IsLeapYear(date) ? 366 : 365;
}

No comments:

Post a Comment