Powershell查询日期之间的日期


如果你需要知道两个日期之间的天数,你可以非常轻松的通过 New-TimeSpan获得:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$difference.Days

然而,你可能不只需要知道他们之间有多少天,还需要详细的天数,这里又有一个方法:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$days = [Math]::Ceiling($difference.TotalDays)+1

1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
}

这次,Powershell输出了两个指定日期之间全部的日期。

现在你应该知道准确的时间了(不仅是天数),同时你还可以筛选,例如列出工作日和算出好多个星期天或好多天后你能过节或退休。

这里仅获得你的工作天数:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$difference.Days

$days = [Math]::Ceiling($difference.TotalDays)+1

1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
} |
  Where-Object { $_.DayOfWeek -gt 0 -and $_.DayOfWeek -lt 6}
"And this counts the working days:"

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
"Days in all: " + $difference.Days

$days = [Math]::Ceiling($difference.TotalDays)+1

$workdays = 1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
} |
  Where-Object { $_.DayOfWeek -gt 0 -and $_.DayOfWeek -lt 6} |
  Measure-Object |
  Select-Object -ExpandProperty Count

"Workdays: $workdays"

原文地址:Finding Dates Between Two Dates

 

×用微信扫描并分享
本文链接: https://www.pstips.net/finding-dates-between-two-dates.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注