February 2, 2011

Get the date for a specific day of the week

Ever needed a way to get the date for a specific day of the week (i.e. The date for last Thursday, date next Friday, get date for the next Friday after 2/2/2011, etc.)

I have created an extension method that will help you accomplish that:

/// <summary>
/// Gets the day of week.
/// </summary>
/// <param name="date">Baseline Date .</param>
/// <param name="day">The day you want to find.</param>
/// <param name="inFuture">if set to true, then looks into the future, else it looks in the past</param>
/// <param name="includeToday">if set to <c>true</c> it includes the date's day when searching.</param>
/// <returns></returns>
public static DateTime GetDayOfWeek(this DateTime date, DayOfWeek day, bool inFuture, bool includeToday)
{
    DateTime currentDate = date;
 
    bool sameDay = true;
    while (true)
    {
        if (currentDate.DayOfWeek == day && (includeToday || !sameDay))
        {
            return new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);
        }
 
        if (currentDate > DateTime.MaxValue.AddDays(-1) ||
            currentDate < DateTime.MinValue.AddDays(1))
        {
            throw new ArgumentOutOfRangeException(currentDate + " is out of range");
        }
 
        currentDate = currentDate.AddDays(inFuture ? 1 : -1);
        sameDay = false;
    }
}
Hope this helps you!

No comments:

Post a Comment