Monday, June 06, 2005

 

Get the N-th Monday of the Month (VB.NET)

I needed a way to find the n-th Monday of a month, so this is the best way that I could find.
Private Function GetNthMondayOfMonth(ByVal GivenDate As Date, ByVal N As Integer) As Date
'This function returns the date of the Nth Monday of the month in the given date
'If there are not N Mondays in the month, the last Monday of the month is returned
Dim SixthDayOfMonth As Date = GivenDate.AddDays(6 - GivenDate.Day)
Dim FirstMondayOfMonth As Date = SixthDayOfMonth.AddDays(1 - SixthDayOfMonth.DayOfWeek)
Dim NthMondayOfMonth As Date = FirstMondayOfMonth.AddDays(7 * (N - 1))
'check if N Mondays went into another month (or wrapped around so far it is a different year)
If GivenDate.Month <> NthMondayOfMonth.Month Or GivenDate.Year <> NthMondayOfMonth.Year Then
'Figure out the last Monday of the month and use that
Dim LastDayOfMonth As Date = GivenDate.AddDays(Date.DaysInMonth(GivenDate.Year, GivenDate.Month) - GivenDate.Day)
Dim LastMondayOfMonth As Date = LastDayOfMonth.AddDays(1 - LastDayOfMonth.DayOfWeek)
NthMondayOfMonth = LastMondayOfMonth
End If
GetNthMondayOfMonth = NthMondayOfMonth
End Function

This page is powered by Blogger. Isn't yours?