PowerShell 在 2020 年 1 月 6 日返回周数为 2。

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 21:56:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定