Thursday, September 13, 2012

Start of Week

Needed to find the first day of the next week for a given date. I thought there might be an in-built method to do this, but I didn't see anything.

So I wrote these extension methods - one that uses the CurrentCulture and one that can work on a predefined day of the week.
public static class DateTimeExtensions
{
    public static DateTime GetNextWeekStartDate(this DateTime dt, 
                                                DayOfWeek weekStartDay)
    {
        var difference = weekStartDay - dt.DayOfWeek;
        if (difference < 0)
            difference += 7;
        return dt.AddDays(weekStartDay - dt.DayOfWeek + 7);
    }

    public static DateTime GetNextWeekStartDate(this DateTime dt)
    {
        CultureInfo ci = Thread.CurrentThread.CurrentCulture;
        DayOfWeek weekStartDay = ci.DateTimeFormat.FirstDayOfWeek;
        return GetNextWeekStartDate(dt, weekStartDay);
    }
}

But I hate adding the 7 there. I am sure this can be done in  a more elegant way. Another time perhaps...

No comments:

Post a Comment