PowerShell: Get the week number for a given date

I was working on some reporting in PowerShell this afternoon, and needed to figure out if two dates are in the same week.

Here’s a quick little function that I put together to get the week number given a specific date. If no [datetime] object is passed in, it will simply return the week number for the current date.

A screenshot showing the Get-WeekNumber function in action. Called without the DateTime parameter, it outputs week 35. Given an input of "11 march 2015", it outputs 11.

Screenshot of Get-WeekNumber in action

Here’s the code:

# Removed my original snippet. See comments below from Bart.
# The below example is courtesy of Bart.
function Get-ISO8601Week {
[datetime]$DT = (Get-Date)
First create an integer(0/1) from the boolean,
"Is the integer DayOfWeek value greater than zero?".
Then Multiply it with 4 or 6 (weekrule = 0 or 2) minus the integer DayOfWeek value.
This turns every day (except Sunday) into Thursday.
Then return the ISO8601 WeekNumber.
$Cult = Get-Culture; $DT = Get-Date($DT)
$WeekRule = $Cult.DateTimeFormat.CalendarWeekRule.value__
$FirstDayOfWeek = $Cult.DateTimeFormat.FirstDayOfWeek.value__
$WeekRuleDay = [int]($DT.DayOfWeek.Value__ -ge $FirstDayOfWeek ) * ( (6 $WeekRule) $DT.DayOfWeek.Value__ )
$Cult.Calendar.GetWeekOfYear(($DT).AddDays($WeekRuleDay), $WeekRule, $FirstDayOfWeek)

view raw
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s