Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

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?

like image 942
Elisabeth Avatar asked Nov 09 '10 22:11

Elisabeth


1 Answers

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);
like image 114
Henk Holterman Avatar answered Sep 21 '22 11:09

Henk Holterman