PowerShell for Seasons
I wrote this little snippet to assist me with working out the current season (as in Spring, Summer, Autumn and Winter) with an accuracy of +/- 2 days. No, it’s not a method of calculating the exact time and date that the equinoxes will occur in a certain hemisphere but it’s good enough. I should mention that this is for the Northern Hemisphere so if you want one for the Southern Hemisphere, it should be pretty simple to work out what to change! The function will tell you the current season (if you don’t provide a date) or the season of a certain date you give it.
I looked at Wikipedia to see the next dates of the Equinoxes and they all fall on or around the dates below with an accuracy of +/- 2 days. If you want hyper-accuracy, don’t use this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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 based on # the average of dates over the next 5 years or so. Generally, these dates may be # inaccurate by at most one or two days +/- . Equinox calculations these are not. $Winter = Get-Date "01/01/$($Date.Year)" $Spring = Get-Date "20/03/$($Date.Year)" $Summer = Get-Date "21/06/$($Date.Year)" $Autumn = Get-Date "22/09/$($Date.Year)" $Winter2 = Get-Date "21/12/$($Date.Year)" switch($Date) { {($_ -ge $Winter) -and ($_ -le $Spring)} {return "Winter"} {($_ -ge $Spring) -and ($_ -le $Summer)} {return "Spring"} {($_ -ge $Summer) -and ($_ -le $Autumn)} {return "Summer"} {($_ -ge $Autumn) -and ($_ -le $Winter2)} {return "Autumn"} {($_ -ge $Winter2) -and ($_ -le $Spring.AddYears(1))} {return "Winter"} } } Get-Season -Date (Get-Date "25/12/2016") # Winter Get-Season # Summer (as of 21/09/2016) |
Stating the obvious, one has to be aware of the local PC’s default locale date format and adjust the script accordingly. DD/MM vs MM/DD 🙂 Nice work.
Ha, yes! Good call Wayne, thanks.