英文:
PowerShell returns 2 as week number on January 06 2020
问题
今天(2020年1月6日)的星期数应该是2,因为2020年有53周。然而,以下PowerShell代码片段返回1:
(Get-Date -UFormat %V)
如何正确获取星期数的良好方法是什么?
英文:
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?
答案1
得分: 3
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
英文:
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
答案2
得分: 1
你可以检测闰年,然后根据结果调整周数。
if(((Get-Date).year)%4 -eq 0){
$week = (Get-Date -UFormat %V) -as [int]
$week++
}else{
$week = (Get-Date -UFormat %V)
}
Write-Host $week
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论