确定季节

Determining season

我正在制作一个根据日期确定季节的脚本。这是我目前所拥有的:

#$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

spring 中的日期似乎在夏季和秋季按预期工作,但冬季则不然。我怀疑这是因为 PowerShell 不理解日期(例如 02-22)如何同时大于第 12 个月和小于第 2 个月。

我想我可以用一个又长又难看的语句来解决这个问题(比如在里面多放几个 -and 运算符和括号,或者使用 -or 运算符,但我更感兴趣的是了解处理此问题的最佳 practice/most 有效方法。

已经提到的xy 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

处理 2 月 29 日结束的闰年。虽然这不是冬季结束时间的典型定义,但 "season" 可能与商业或体育活动有关,其中在月底结束更有意义。

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