Search code examples
powershellweek-numbergetdate

PowerShell returns 2 as week number on January 06 2020


A quick question, apparently today (January 06, 2020) week number should be 2, because there are 53 weeks in 2020.

However, the following PowerShell snippet returns 1:

(Get-Date -UFormat %V)

What is the good approach getting the week number properly?


Solution

  • To translate this Get the correct week number of a given date C# answer from @il_guru into PowerShell:

    Function GetIso8601WeekOfYear([DateTime]$Date) {
        $Day = (Get-Culture).Calendar.GetDayOfWeek($Date)
        if ($Day -ge [DayOfWeek]::Monday -and $Day -le [DayOfWeek]::Wednesday) {$Date = $Date.AddDays(3)}
        (Get-Culture).Calendar.GetWeekOfYear($Date, 'FirstFourDayWeek', 'Monday')
    }
    GetIso8601WeekOfYear (Get-Date)
    2
    GetIso8601WeekOfYear (Get-Date('2016-01-01'))
    53