PowerShell returns 2 作为 2020 年 1 月 6 日的周数
PowerShell returns 2 as week number on January 06 2020
一个简单的问题,显然今天(2020年1月06日)周数应该是2,因为2020年有53周。
但是,以下 PowerShell 片段 returns1:
(Get-Date -UFormat %V)
正确获取周数的好方法是什么?
您可以检测闰年,然后根据结果调整周数。
if(((Get-Date).year)%4 -eq 0){
$week = (Get-Date -UFormat %V) -as [int]
$week++
}else{
$week = (Get-Date -UFormat %V)
}
Write-Host $week
将此 Get the correct week number of a given date C# answer from @il_guru 翻译成 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
一个简单的问题,显然今天(2020年1月06日)周数应该是2,因为2020年有53周。
但是,以下 PowerShell 片段 returns1:
(Get-Date -UFormat %V)
正确获取周数的好方法是什么?
您可以检测闰年,然后根据结果调整周数。
if(((Get-Date).year)%4 -eq 0){
$week = (Get-Date -UFormat %V) -as [int]
$week++
}else{
$week = (Get-Date -UFormat %V)
}
Write-Host $week
将此 Get the correct week number of a given date C# answer from @il_guru 翻译成 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