John Kaster

Behind the Screen

Archive for the ‘c#’ Category

Working for the weekend

with 4 comments

At Transactis, one of the utility methods I’d been meaning to develop was the calculation of weekend days (Saturday and Sunday) between two dates. I wanted something that was LINQ-able for the collection of dates in the range. After an entertaining Skype chat with Tim Jarvis, a friend of mine who does not work at Transactis, but is a certifiable LINQ nut, this was the end result, which is contained in the Utility class UT.cs:

        public static IEnumerable<DateTime> GetWeekends(int year)
        {
            DateTime fromDate = new DateTime(year, 1, 1);
            DateTime toDate = new DateTime(year, 12, 31);
            return GetWeekends(fromDate, toDate);
        }

        public static IEnumerable<DateTime> GetWeekends(DateTime fromDate, DateTime toDate)
        {
            if (fromDate.DayOfWeek == DayOfWeek.Sunday)
            {
                yield return fromDate; // Add end of weekend to this result
                fromDate = GetNextDateForDay(fromDate, DayOfWeek.Saturday);
            }
            else if (fromDate.DayOfWeek != DayOfWeek.Saturday)
                fromDate = GetNextDateForDay(fromDate, DayOfWeek.Saturday);
            TimeSpan ts = toDate - fromDate; // Days from current weekend date to EOY
            int daysToAdd = ts.Days;
            for (int i = 0; i <= daysToAdd; i += 7)
            {
                yield return fromDate.AddDays(i);
                if (i+1 < daysToAdd)
                    yield return fromDate.AddDays(i + 1);
            }
        }

 

(This code uses GetNextDateForDay() from the excellent blog post http://angstrey.com/index.php/2009/04/25/finding-the-next-date-for-day-of-week/.)

The typical usage scenario for us is assigning all weekend days for a given year. This led to the following int extension method:

    public static class IntUtil
    {
        public static IEnumerable<DateTime> GetWeekends(this int year)
        {
            return UT.GetWeekends(year);
        }
    }

 

With this int overload, it’s now a trivial matter to get an enumeration of all weekend days for any year:

var lastYear = 2010.GetWeekends();
var thisYear = 2011.GetWeekends();
var nextYear = 2011.GetWeekends();

 

I hope you find this technique useful for something you need. One obvious one would be getting a specific day of the week for a given date range, not just Saturday and Sunday. This routine is specifically optimized to return that pair of dates.

 

P.S. Thanks to Scott, he-who-is-not-a-fool who answered my tweet question about a good source code plug-in for Windows Live Writer on WordPress.com hosted blogs. You can get his plug-in from his website.

Advertisements

Written by John Kaster

May 25, 2011 at 6:35 am

Posted in c#, LINQ