Reputation: 21206
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
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
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
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
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
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