Get the next and past day of the week

Say you want to know what day is going to be next Friday from now or from a specific date. Say you also want to know what day was last Friday from now or from a specific date. Use these methods to find out:

/// <summary>
/// Gets the past date before the specified date
/// </summary>
/// <param name="date">the specified date</param>
/// <param name="dayOfWeek">Day of the week to get the date</param>
/// <returns></returns>
public static DateTime GetPastDate(DateTime date, DayOfWeek dayOfWeek)
{
    DateTime weekDate = date;

    if (weekDate.DayOfWeek != dayOfWeek)
    {
        do
        {
            DateTime temp = weekDate.AddDays(-1);
            weekDate = new DateTime(temp.Year, temp.Month, temp.Day);
        } while (weekDate.DayOfWeek != dayOfWeek);
    }

    return weekDate;
}

/// <summary>
/// Gets the next date after the specified date
/// </summary>
/// <param name="date">the specified date</param>
/// <param name="dayOfWeek">Day of the week to get the date</param>
/// <returns></returns>
public static DateTime GetNextDate(DateTime date, DayOfWeek dayOfWeek)
{
    DateTime weekDate = date;

    if (weekDate.DayOfWeek != dayOfWeek)
    {
        do
        {
            DateTime temp = weekDate.AddDays(1);
            weekDate = new DateTime(temp.Year, temp.Month, temp.Day);
        } while (weekDate.DayOfWeek != dayOfWeek);
    }

    return weekDate;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s