如何用PowerShell计算今日起第6/20个工作日?附示例
计算指定起始日期后的第N个工作日(PowerShell实现)
嘿,我刚好有个实用的PowerShell函数可以解决你的两个需求,不管是第6个还是第20个工作日,都能轻松搞定!这个函数默认排除周六和周日,如果你需要加入节假日的话,也可以很方便地扩展它。
通用函数:Get-NthWorkday
function Get-NthWorkday { [CmdletBinding()] param( # 起始日期,默认是当前日期 [DateTime]$StartDate = (Get-Date), # 要获取的第N个工作日 [int]$NthDay ) $currentDate = $StartDate $workdayCount = 0 while ($workdayCount -lt $NthDay) { # 日期往后推一天 $currentDate = $currentDate.AddDays(1) # 判断是否是工作日(排除周六和周日) if ($currentDate.DayOfWeek -notin [DayOfWeek]::Saturday, [DayOfWeek]::Sunday) { $workdayCount++ } } return $currentDate }
需求1:计算今日起第20个工作日
直接调用函数,指定-NthDay 20即可:
Get-NthWorkday -NthDay 20
运行后会返回从今天开始数的第20个工作日日期。
需求2:计算指定日期起第6个工作日(含示例验证)
针对你给出的示例:起始日期是2018年2月4日,要获取第6个工作日。可以这样调用函数:
Get-NthWorkday -StartDate '2018-02-04' -NthDay 6
运行结果会返回2018-02-12,和你给出的示例完全一致!
扩展:加入节假日判断
如果你的场景需要排除法定节假日,可以修改函数,加入一个节假日数组,比如:
function Get-NthWorkdayWithHolidays { [CmdletBinding()] param( [DateTime]$StartDate = (Get-Date), [int]$NthDay, # 自定义节假日数组,格式为DateTime对象 [DateTime[]]$Holidays ) $currentDate = $StartDate $workdayCount = 0 while ($workdayCount -lt $NthDay) { $currentDate = $currentDate.AddDays(1) # 同时排除周末和指定节假日 if ($currentDate.DayOfWeek -notin [DayOfWeek]::Saturday, [DayOfWeek]::Sunday -and $currentDate -notin $Holidays) { $workdayCount++ } } return $currentDate }
使用时只需传入节假日列表:
$holidays = @('2024-01-01', '2024-02-10') | Get-Date Get-NthWorkdayWithHolidays -NthDay 6 -Holidays $holidays
内容的提问来源于stack exchange,提问作者sumanth
相关产品推荐
相关产品推荐

