1

I need to find the date of the third saturday of the month.

I've got the following function, which finds me the last saturday of the month

function Get-3rdSaturdayOfMonth {
    $Date = Get-Date
    $lastDay = new-object DateTime($Date.Year, $Date.Month, [DateTime]::DaysInMonth($Date.Year, $Date.Month))
    $diff = ([int] [DayOfWeek]::Saturday) - ([int] $lastDay.DayOfWeek)
    if ($diff -ge 0) {
        return $lastDay.AddDays(- (7-$diff))
    }
    else {
        return $lastDay.AddDays($diff)
    }
}

However, I don't know how to edit it to find the third saturday of the month.

Right now the function goes from last date of the month to the saturday that comes before it. But if I want the third saturday i think i need to calculate from the first day of the month, not the last.

SimonS
  • 1,701
  • 1
  • 25
  • 50

1 Answers1

2

Based on the solution from Brandon, since the third Saturday can't possibly occur before the 15th of the month, we can increment from the 15. until we find a saturday:

$thirdSaturday = [DateTime]::new((Get-Date).Year,(Get-Date).Month,15)
while ($thirdSaturday.DayOfWeek -ne [DayOfWeek]::Saturday) 
{
    $thirdSaturday = $thirdSaturday.AddDays(1)
}
Martin Brandl
  • 51,813
  • 12
  • 118
  • 151