dotNetChris @ Marisic.Net

January 14, 2009

Method to determine if data range contains a leap year

Filed under: Programming — Tags: , , — dotnetchris @ 7:17 pm

Update 1/14/2008: I pulled a Microsoft zune! My leap check was actually off by 1. Corrected algorithm

As I was going through some of code I previously worked on today I came across this method I wrote a while ago. I’m not too sure  if it will help anyone else but I figured I’d throw it up here. Basically I had a need to figure out if a date entered was inside a period of time in the future (in my case specifically 2.5 years and 3.0 years in the future). My original plan was to just check if number of days fit in between 365*2.5  and 365*3 but I realized as rare of a possiblity as it was a potential leap year could have foiled my plans.

So basically I wrote this method for me to be able to calculate if I need to add another day to my range to make sure they weren’t short changed a day because leap year occurred.

I’d love to hear your opinions on this code if there is anything you’d do differently.

/// <summary>
/// Determines if the DateRange contains a leap year.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns></returns>
private static bool DateRangeContainsLeapYear(DateTime startDate, DateTime endDate)
{
  if (startDate > endDate)
    throw new InvalidDataException("startDate must be less than or equal to endDate.");

  //Bounds check Feb will exist either in start of the first time span date
  //or at the end of the last date potentially
  if (startDate.Month < 3 && DateTime.IsLeapYear(startDate.Year))
    return true;
  if ((endDate.Month > 3 || (endDate.Month == 2 && endDate.Day == 29))
&& DateTime.IsLeapYear(endDate.Year))
    return true;

  //Start year can't be leap year otherwise we're done
  int startYear = startDate.Year + 1;

//Upper bounds will be handled by i < endYear
  int endYear = endDate.Year;

  for (int year = startYear; year < endYear; year++)
  {
    if(!DateTime.IsLeapYear(year)) continue;
    return true;
  }

  return false;
}

BloggingContext.ApplicationInstance.CompleteRequest();

2 Comments »

  1. You should add another parameter that lets you define whether the validation is inclusive or exclusive. Looks good. Great Job.

    Comment by Khalid Abuhakmeh — December 10, 2008 @ 6:58 pm

    • That is a good call.

      Comment by dotnetchris — December 10, 2008 @ 8:12 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.