网站搜索

星期五乐趣:使用 PowerShell 获取一年中的某一天


虽然我可以轻松找出给定日期是一年中的哪一天:

([datetime]"7/4/2013").dayOfYear

没有方法将整数转换为一年中的某一天。但这确实没那么难。这是一个简单的函数。

<#
.Synopsis
Get day of year
.Description
Get the day of the year for a given integer. The default year is the current.
#>
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter an integer for the day of the year.")]
[ValidateRange(1,366)]
[int]$DayOfYear,
[ValidateRange(1,9999)]
[int]$Year=(Get-Date).Year
)

#define the first day of the year
[datetime]$dt= "1/1/$Year"

#the smart way
$dt.AddDays($DayOfYear-1)

<# 
Ignore this. It is the "hard" way. I clearly was overthinking this. 
#loop through each day of the year and compare it to the target day of the year 
While ( $dt.DayOfyear -ne $dayofYear) {
    $dt = $dt.AddDays(1)  
}  
#write the final date 
$dt.Date
#>

} #close function

命令周围的内容比命令本身还要长。但我不介意。该函数采用 1 到 366 之间的整数值,即一年中最多可能的天数。您还可以指定年份,但默认为当前年份。 然后,该函数使用 While 循环进行循环,该循环不断添加一天,直到一年中的某一天与一年中的目标日期相匹配。我使用了 While 循环,因为表达式有可能立即为 True,并且无需处理脚本块。 复制并粘贴代码并亲自尝试!

更新:我一发布就知道有人会向我展示更好的方法。他们做到了。我显然对这个问题想得太多了。我更新了代码以展示执行此操作的智能方法。现在解决方案如此之短,您可能甚至不需要该功能。

相关文章