2 minutes
Nth Day of Month
Introduction
Recently I was wanting to set up some reminders for important dates. While working on that I thought it would be nice to add regular holidays to that. For some holidays, that’s not a big deal. February 14 is St. Valentine’s day every year. But what about those holidays that move around. For example, Mother’s Day is the second Sunday in May. Memorial Day is the last Monday in May.
I decided to create a function I could call to get the date for these moving targets. The idea is to pass the month, the day in question and which one you want.
Getting the Nth Day of the Month
function Get-NthDayOfMonth {
param(
[int]$Month, #int 1-12
[int]$WeekDay, #int 0-6
[int]$NthDay #1-5,-1 for last of.
)
Start with 1st day of month.
$startdate = get-date -Month $Month -Day 1
With no year passed, PowerShell uses the current year. If date is in the past add a year.
if($startdate -lt (get-date)){
$startdate = $startdate.AddYears(1)
}
Check for -1 to get last x of the month. We then go to 1st of next month and backtrack 8 days. I use -1 since that’s also the index for the last element in an array.
if($NthDay -eq -1){
$startdate = ($startdate.AddMonths(1)).AddDays(-8)
}
Loop through days until we get the first day we’re looking for. value__
is the numerical value of the day of the week starting at zero for Sunday.
While($startdate.DayOfWeek.value__ -ne $WeekDay){
$startdate = $startdate.AddDays(1)
}
If we’re looking for the last x of the month, we started in the last week so we’re done.
If we’re looking for first x of the month, 7 * (1 - 1) evaluates to 0 so AddDays of zero leaves us where we’re at. For all other days we move forward the appropriate number of weeks to get what we want. We subtract one because we already found the first one.
There is no check for looking for a day past the end of the month. Looking for the 7th Tuesday in June will give you a date in July.
if($NthDay -eq -1){
$startdate
}else{
$startdate = $startdate.AddDays( 7 * ($NthDay - 1))
$startdate
}
}
A fairly simple solution to my problem. Once I got past this, I started thinking about weird calendar events like solstice and Easter. That will be a different blog post.
Thanks for reading.
Comments powered by Talkyard.