logo  How To find First, Second, ... Weekday in Month
This Chapter
Date Functions
Advent
Bank Hol (UK)
Chinese Calendar
Easter
Easter-Orthodox
Epoch Dates
Hebrew Calendar
Iso-Week Calendar
Nearest Weekday
Week Of Month
Other Dates
Chapters
Home Page
Colours, RGB
Computer Specifications
Dates&Times
Disk Drives
Files
Folders
GPS and OS Ref
VB.Net Forms
Image Files
If & Select
List/Array
Mathematics
NuGet
Sound
String Functions
Sun and Moon
User Controls
Validation
DigitalDan Sites
My Other Sites
Contact Site

Note
Some pages
may contain
inaccuracies
Hits=5
This function caluclates dates for the first, second, third, fourth or last occurence of any DayfWeek within a month. A typical application would be to find the date of a UK Bank Holiday. (They often fall on first or last Monday of a month.) I have included some examples demonstrating how to use this function
 
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