2

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?

Sherzad
  • 405
  • 4
  • 14
  • PowerShell defers to .NET for this, and .NET does not quite implement the ISO week number, as per [this question](https://stackoverflow.com/questions/11154673/get-the-correct-week-number-of-a-given-date). The code snippets that fix this could be imported directly into PowerShell with `Add-Type`, or else the code is fairly easily converted directly to PowerShell. – Jeroen Mostert Jan 06 '20 at 14:07
  • Incidentally, the total number of weeks in the year is not relevant. The reason the (ISO) week number is 2 is because the previous week was 1, and the reason that week was 1 is because it's the week containing the first Thursday. This year has 53 ISO weeks because it's a leap year starting on Wednesday, but that's not an equivalent property. – Jeroen Mostert Jan 06 '20 at 15:58

2 Answers2

3

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
iRon
  • 20,463
  • 10
  • 53
  • 79
1

You could detect a leap year and then adjust the week number based off the result.

if(((Get-Date).year)%4 -eq 0){
    $week = (Get-Date -UFormat %V) -as [int]
    $week++
}else{
    $week = (Get-Date -UFormat %V)
}
Write-Host $week
jman_pS
  • 29
  • 3
  • 2
    It seems it is not only sufficient to calculate the modulus by 4, other conditions also should be considered like this: ` $currentYear = (Get-Date -f yyyy) if ( ( ($currentYear % 4 -eq 0) -and ($currentYear % 100 -ne 0) ) -or ($currentYear % 400 -eq 0) ) { Write-Host "Leap" } else { Write-Host "No Leap" }` – Sherzad Jan 06 '20 at 15:06
  • I agree with @Abdul Rahman Sherzad, you can't just look to a leap year and add a week as that would e.g. return **`54`** for **`1 jan 2016`**. – iRon Jan 06 '20 at 15:32