views:

105

answers:

3

Ok, so I need to find the date of Monday this week programmatically.

For example, for this week Monday was on the 9th, so the date I need is: 09/11/2009

And when we roll over to next week it needs to calculate: 16/11/2009

I have tried doing this myself but I can't see how to do the arithmetic, thank you.

+1  A: 

C#:

date.AddDays(1 - (date.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)date.DayOfWeek));

VB.NET:

date.AddDays(1 - IIf((date.DayOfWeek = DayOfWeek.Sunday), 7, date.DayOfWeek))
najmeddine
Nice one-liner there.
ck
When I use that I get a lot of syntax errors, and when I clean it up to what .NET might accept I get this error: Value of type 'Date' cannot be converted to 'Integer'
Gordon
That's because that is C# and not vb.net
RobS
I edited my answer to include VB.NET version.
najmeddine
I'd use If instead of Iif though if possible (short-circuiting + type safe)
Meta-Knight
+1  A: 

Dim thisMonday As Date = Now.AddDays((Now.DayOfWeek - 1) * -1).Date

'if today is a Sunday it gives the following Monday otherwise, gives the Monday this week.

Martin
+1  A: 

Return givenDate.AddDays(1 - CType(IIf((givenDate.DayOfWeek = DayOfWeek.Sunday), 7, givenDate.DayOfWeek), Double))

If givenDate is a Sunday, counts back to the preceding Monday. Includes a CType to cast the IIf result to a Double to work with Option Strict On.

PhilPursglove