PowerShell Function to Determine Daylight Saving Time
About a year ago, I wrote a PowerShell one-liner to Calculate What Date Thanksgiving is on with PowerShell (in the United States). When looking back at that blog now, my first thought is boy that is some rough code that's hard to read. Instead of re-writing the same thing again, I decided to write something similar applying what I've learned during the past year to it.
That's how I came up with the idea to write a PowerShell function that returns the beginning and ending dates for daylight saving time in the USA for a given year or years:
1#Requires -Version 3.0
2function Get-DayLightSavingTime {
3
4<#
5.SYNOPSIS
6 Returns the beginning and ending date for daylight saving time.
7.DESCRIPTION
8 Get-DayLightSavingTime is a function that returns the dates when
9 daylight saving time begins and ends for the specified year.
10.PARAMETER Year
11 The year to return the daylight saving time dates for. The year cannot
12 be earlier than 2007 because the dates were in April and October instead
13 of March and November prior to that year. The default is the current year.
14.EXAMPLE
15 Get-DayLightSavingTime
16.EXAMPLE
17 Get-DayLightSavingTime -Year 2014, 2015
18.EXAMPLE
19 Get-DayLightSavingTime -Year (2011..2020)
20.EXAMPLE
21 2014, 2015 | Get-DayLightSavingTime
22.EXAMPLE
23 2011..2020 | Get-DayLightSavingTime
24.INPUTS
25 Integer
26.OUTPUTS
27 PSCustomObject
28.NOTES
29 Written by Mike F Robbins
30 Blog: http://mikefrobbins.com
31 Twitter: @mikefrobbins
32#>
33
34 [CmdletBinding()]
35 param (
36 [Parameter(ValueFromPipeline)]
37 [ValidateRange(2007,9999)]
38 [Int[]]$Year = (Get-Date).Year
39 )
40
41 PROCESS {
42 foreach ($y in $Year) {
43
44 [datetime]$beginDate = "March 1, $y"
45
46 while ($beginDate.DayOfWeek -ne 'Sunday') {
47 $beginDate = $beginDate.AddDays(1)
48 }
49
50 [datetime]$endDate = "November 1, $y"
51
52 while ($endDate.DayOfWeek -ne 'Sunday') {
53 $endDate = $endDate.AddDays(1)
54 }
55
56 [PSCustomObject]@{
57 'Year' = $y
58 'BeginDate' = $($beginDate.AddDays(7).AddHours(2))
59 'EndDate' = $($endDate.AddHours(2))
60 }
61
62 }
63 }
64}
I can't say that I've seen someone accept multiple integers before, this is something I normally see with strings but it appears to work without issue.
The really cool thing is that you can use the range operator to pipe in a range of years:
You can also use the range operator to specify a range of years via parameter input:
µ