确定季节

时间:2018-06-21 17:13:28

标签: powershell powershell-v3.0

我正在制作一个脚本,该脚本根据日期确定季节。这是我到目前为止的内容:

#$currentDate = Get-Date -Format "MM-dd"
$currentDate = Get-Date 02-22

# Determining season
if ($currentDate -ge (get-date 03-01) -and $currentDate -le (get-date 05-31)) {
    $season = "Spring"
} elseif ($currentDate -ge (get-date 06-01) -and $currentDate -le (get-date 08-31)) {
    $season = "Summer"
} elseif ($currentDate -ge (get-date 09-01) -and $currentDate -le (get-date 11-30)) {
    $season = "Fall"
} elseif ($currentDate -ge (get-date 12-01) -and $currentDate -le (get-date 02-29)) {
    $season = "Winter"
} else {
    "Ryan Messed up"
    $season = "ERROR"
}

$season

看来,春季,夏季和秋季的日期按预期工作,但冬季却没有。我怀疑这是因为PowerShell无法理解日期(例如02-22)如何大于第12个月并且小于第2个月。

我想我可以用冗长而丑陋的语句来解决此问题(例如在其中添加更多-and运算符和括号,或者使用-or运算符,但我对了解最佳实践/最有效的解决方法。

2 个答案:

答案 0 :(得分:1)

已经提到的function Get-Season 简化了一点,使区域设置更加独立:

Function Get-Season([datetime]$Date){
    If (!$Date) {$Date = Get-Date} #If date was not provided, assume today.
    # The dates are obviously not exactly accurate and are best guesses
    $Spring = Get-Date -Day 20 -Month 03 -Year $Date.Year
    $Summer = Get-Date -Day 21 -Month 06 -Year $Date.Year
    $Autumn = Get-Date -Day 22 -Month 09 -Year $Date.Year
    $Winter = Get-Date -Day 21 -Month 12 -Year $Date.Year
    $Season = switch($Date) {
        {($_ -lt $Spring)}  {"Winter";Break}
        {($_ -lt $Summer)}  {"Spring";Break}
        {($_ -lt $Autumn)}  {"Summer";Break}
        {($_ -lt $Winter)}  {"Autumn";Break}
        {($_ -ge $Winter)}  {"Winter"}
    }
    "{0:d} is in season {1}" -f $Date,$Season
}

示例输出(我的语言环境短日期格式为yyyy-MM-dd)

> Get-Season
2018-06-21 is in season Summer

> Get-Season (Get-Date).adddays(-1)
2018-06-20 is in season Spring

答案 1 :(得分:1)

处理leap年,其中2月29日结束。虽然这不是冬季结束时间的典型定义,但“季节”可能与商务或体育活动有关,在这个月份的最后一天更有意义。

param (
    [DateTime] $Date = (Get-Date -Format "MM-dd")
)

$endOfFebruary = "02-28"
try {
    $date = Get-Date 02-29
    if ($date -ne $null) { $endOfFebruary = $date.ToString("mm-dd") }
}
catch {
}

$seasons = @{
    Spring = @{ Start = "03-01"; End = "05-31" };
    Summer = @{ Start = "06-01"; End = "08-31" };
    Fall   = @{ Start = "09-01"; End = "11-30" };
    Winter = @{ Start = "12-01"; End = $endOfFebruary };
}

$currentSeason = $null

foreach ($season in $seasons.Keys)
{
    $start = Get-Date $seasons[$season].Start
    $end = Get-Date $seasons[$season].End
    if ($season -eq "Winter") {
        if ($Date -ge $start -or $Date -le $end) { $currentSeason = $season }
    } else {
        if ($Date -ge $start -and $Date -le $end) { $currentSeason = $season }
    }
}

Return $currentSeason

输出

PS C:\Code\PowerShell> .\Get-Season.ps1 -Date (Get-Date "04-15")
Spring
PS C:\Code\PowerShell> .\Get-Season.ps1 -Date (Get-Date "07-15")
Summer
PS C:\Code\PowerShell> .\Get-Season.ps1 -Date (Get-Date "12-14")
Winter
PS C:\Code\PowerShell> .\Get-Season.ps1 -Date (Get-Date "11-14")
Fall