Elisabeth
Elisabeth

Reputation: 21206

Get the Monday and Sunday for a certain DateTime in C#

I have a for example the date "2010-11-09, Thuesday"

Now I want to get the datetime of the Monday and Sunday wherein lies the above stated date.

How would you do that?

Upvotes: 10

Views: 26460

Answers (5)

Henk Holterman
Henk Holterman

Reputation: 273244

This is probaly what you're after:

 DateTime date = DateTime.Today;

 // lastMonday is always the Monday before nextSunday.
 // When date is a Sunday, lastMonday will be tomorrow.     
 int offset = date.DayOfWeek - DayOfWeek.Monday;     
 DateTime lastMonday = date.AddDays(-offset);
 DateTime nextSunday = lastMonday.AddDays(6);

Edit: since lastMonday is not always what the name suggests (see the comments), the following one-liner is probably more to the point:

 DateTime nextSunday = date.AddDays(7 - (int) date.DayOfWeek);

Upvotes: 47

user2448969
user2448969

Reputation: 11

/// <summary>
/// Returns the day that is the specific day of week of the input day.
/// </summary>
/// <param name="input">The input day.</param>
/// <param name="dayOfWeek">0 is Monday, 6 is Sunday.</param>
/// <returns></returns>
public static DateTime GetDayOfWeekOfSpecific(DateTime input, int dayOfWeek)
{
    if(input.DayOfWeek == DayOfWeek.Sunday)
    {
        dayOfWeek -= 7;
    }
    // lastMonday is always the Monday before nextSunday.
    // When today is a Sunday, lastMonday will be tomorrow.     
    int offset = input.DayOfWeek - DayOfWeek.Monday;
    DateTime lastMonday = input.AddDays(-offset);
    DateTime nextDayOfWeek = lastMonday.AddDays(dayOfWeek);
    return nextDayOfWeek;
}

Upvotes: 1

ngodungrussia
ngodungrussia

Reputation: 1

It's easily if you use a conditional method

if (v_datetime.DayOfWeek== DayOfWeek.Sunday)
{
return true;
}

if (v_datetime.DayOfWeek== DayOfWeek.Monday)
{

}

Upvotes: -1

light
light

Reputation: 816

DateTime Monday = DateTime.Now.AddDays((DateTime.Now.DayOfWeek - 1) * -1).Date;

DateTime Sunday = DateTime.Now.AddDays(7 -DateTime.Now.DayOfWeek).Date;

Upvotes: 0

dexter
dexter

Reputation: 7203

Something like this, of course you would want to break from the loop at some point before the DateTime.MaxValue, but this should do:

  DateTime dt = DateTime.Parse("2010-11-09, Thuesday");


        while (dt < DateTime.MaxValue) 
        {

            if(dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Monday)
                Console.WriteLine(dt.ToString());
            dt.AddDays(1);
        }

Upvotes: 0

Related Questions