Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the date of monday in a week with VB.NET

I need to find a way to find the date (DD/MM/YYYY) of the Monday for any week we're on.

For example, for this week, monday would be 09/11/2009, and if this were next week it'd be 16/11/2009.

I managed to get somewhere in the forms of code, but all I got was 'cannot convert to Integer' errors. I was using Date.Today and AddDays().

Thanks for any help. :)

like image 509
Willis Avatar asked Nov 10 '09 19:11

Willis


2 Answers

If Sunday is the first day of week, you can simply do this:

Dim today As Date = Date.Today
Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)

If Monday is the first day of week:

Dim today As Date = Date.Today
Dim dayIndex As Integer = today.DayOfWeek
If dayIndex < DayOfWeek.Monday Then
    dayIndex += 7 'Monday is first day of week, no day of week should have a smaller index
End If
Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)
like image 120
Meta-Knight Avatar answered Oct 21 '22 01:10

Meta-Knight


DateTime.DayOfWeek is an enum that indicates what day a given date is. As Monday is 1, you can find the Monday of the current week using the following code:

Dim monday As DateTime = Today.AddDays((Today.DayOfWeek - DayOfWeek.Monday) * -1)
like image 45
Jason Berkan Avatar answered Oct 21 '22 01:10

Jason Berkan