Get Date for nth Day-of-Week of any Month
Private Shared Function DayOfWeek_In_Month(WoM As Week_Of_Month, DoW As DayOfWeek, yyyy As Integer, mm As Integer) As Date
Dim KeyDate As New Date(yyyy, mm, 1, 12, 0, 0, 0, 0)
Dim WeekStartDate As Date
Select Case WoM
Case Week_Of_Month.First : WeekStartDate = New Date(yyyy, mm, 1, 12, 0, 0, 0, 0)
Case Week_Of_Month.Second : WeekStartDate = New Date(yyyy, mm, 8, 12, 0, 0, 0, 0)
Case Week_Of_Month.Third : WeekStartDate = New Date(yyyy, mm, 15, 12, 0, 0, 0, 0)
Case Week_Of_Month.Fourth : WeekStartDate = New Date(yyyy, mm, 22, 12, 0, 0, 0, 0)
Case Week_Of_Month.Last
WeekStartDate = New Date(yyyy, mm, Date.DaysInMonth(yyyy, mm) - 6, 12, 0, 0, 0, 0)
KeyDate = WeekStartDate
End Select
Dim AddDays As Integer = (CInt(DoW) + 7 - CInt(KeyDate.DayOfWeek)) Mod 7
Return WeekStartDate.AddDays(AddDays)
End Function
Public Enum Week_Of_Month
First
Second
Third
Fourth
Last
End Enum
Examples Using DayOfWeek_In_Month Function
On what date was the FIRST MONDAY in JANUARY 2000 (January is month 1)
Dim dat As Date = DayOfWeek_In_Month(Week_Of_Month.First, DayOfWeek.Monday, 2000, 1)
What date was the LAST SUNDAY in JULY 2021 (July is month 7)
Dim dat As Date = DayOfWeek_In_Month(Week_Of_Month.Last, DayOfWeek.Sunday, 2021, 7)
DigitalDan.co.uk