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:

#Requires -Version 3.0
function Get-DayLightSavingTime {

<#
.SYNOPSIS
    Returns the beginning and ending date for daylight saving time.
.DESCRIPTION
    Get-DayLightSavingTime is a function that returns the dates when
    daylight saving time begins and ends for the specified year.
.PARAMETER Year
    The year to return the daylight saving time dates for. The year cannot
    be earlier than 2007 because the dates were in April and October instead
    of March and November prior to that year. The default is the current year.
.EXAMPLE
    Get-DayLightSavingTime
.EXAMPLE
    Get-DayLightSavingTime -Year 2014, 2015
.EXAMPLE
    Get-DayLightSavingTime -Year (2011..2020)
.EXAMPLE
    2014, 2015 | Get-DayLightSavingTime
.EXAMPLE
    2011..2020 | Get-DayLightSavingTime
.INPUTS
    Integer
.OUTPUTS
    PSCustomObject
.NOTES
    Written by Mike F Robbins
    Blog: http://mikefrobbins.com
    Twitter: @mikefrobbins
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [ValidateRange(2007,9999)]
        [Int[]]$Year = (Get-Date).Year
    )

    PROCESS {
        foreach ($y in $Year) {

            [datetime]$beginDate = "March 1, $y"

            while ($beginDate.DayOfWeek -ne 'Sunday') {
                $beginDate = $beginDate.AddDays(1)
            }

            [datetime]$endDate = "November 1, $y"

            while ($endDate.DayOfWeek -ne 'Sunday') {
                $endDate = $endDate.AddDays(1)
            }

            [PSCustomObject]@{
                'Year' = $y
                'BeginDate' = $($beginDate.AddDays(7).AddHours(2))
                'EndDate' = $($endDate.AddHours(2))
            }

        }
    }
}

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:

dst1.png

You can also use the range operator to specify a range of years via parameter input:

dst2.png

ยต