Search code examples
powershellpowershell-3.0

Determining season


I'm making a script that determines the season based on the date. Here's what I have so far:

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

It appears that dates in spring, summer and fall work as intended but winter doesn't. I suspect it is because PowerShell doesn't understand how a date (such as 02-22) can be greater than the 12th month AND less than the 2nd month at the same time.

I think I could fix this with a lengthy and ugly statement (like shoving a few more -and operators and parentheses in there, or use the -or operator but I'm more interested in knowing the best practice/most efficient way to deal with this.


Solution

  • The alreadxy mentioned function Get-Season A bit simplified and made a bit more locale independent:

    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
    }
    

    Sample output (my locale short date format is 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