Hi,
For determining the 2nd Tuesday of the month, there is another way which requires less iteration (therefore potentially faster)
Here a sample, feel free to adjust to your code.
Find the 1st day of the month with the input Date and a day fixed to 1.
$FirstDayOfMonth = Get-Date -Date $Date -Day 1
if ($FirstDayOfMonth.DayOfWeek -like "Tuesday")
{
# We are on the 1st Tuesday of month, then add 7 days
$Output = $FirstDayOfMonth.AddDays(7)
}
else
{
The 1st day of month is not a tuesday, loop and add 1 day at each turn and check if the day is a tuesday
When the first tuesday will be reached, add 7 days to have the 2nd tuesday of month
$FirstDayOfMonth = $FirstDayOfMonth.AddDays(1)
while ($FirstDayOfMonth.DayOfWeek -notlike "Tuesday")
{
$FirstDayOfMonth = $FirstDayOfMonth.AddDays(1)
}
$Output = $FirstDayOfMonth.AddDays(7)
}
The month with the most favorable situation is when the 1st day of the month is a tuesday of course (only one .addays(7) ). The worst is when the 1st day is a wednedday ( .addays(+1) run 6 times + .Adddays(7) once ). With your way, in all cases you iterate 30 times.
Regards
$Output
Regards
Hi,
For determining the 2nd Tuesday of the month, there is another way which requires less iteration (therefore potentially faster)
Here a sample, feel free to adjust to your code.
Find the 1st day of the month with the input Date and a day fixed to 1.
$FirstDayOfMonth = Get-Date -Date $Date -Day 1
if ($FirstDayOfMonth.DayOfWeek -like "Tuesday")
{
# We are on the 1st Tuesday of month, then add 7 days
$Output = $FirstDayOfMonth.AddDays(7)
}
else
{
The 1st day of month is not a tuesday, loop and add 1 day at each turn and check if the day is a tuesday
When the first tuesday will be reached, add 7 days to have the 2nd tuesday of month
$FirstDayOfMonth = $FirstDayOfMonth.AddDays(1)
while ($FirstDayOfMonth.DayOfWeek -notlike "Tuesday")
{
$FirstDayOfMonth = $FirstDayOfMonth.AddDays(1)
}
$Output = $FirstDayOfMonth.AddDays(7)
}
The month with the most favorable situation is when the 1st day of the month is a tuesday of course (only one .addays(7) ). The worst is when the 1st day is a wednedday ( .addays(+1) run 6 times + .Adddays(7) once ). With your way, in all cases you iterate 30 times.
Regards
$Output
Regards