Understanding and Manipulating Dates and Time in PowerShell

Working with Dates and Times in PowerShell is very common. Many scripts require simple or complex date calculations for such things as archiving files or logic to determine what data to operate on. Learn how to effectively work with dates and times in PowerShell in this article using the Get-Date cmdlet, DateTime class, and the New-TimeSpan cmdlet.

Using the Get-Date Command

The number one command to consider when working with dates and times in PowerShell is the Get-Date command. By running Get-Date just by itself, you will output a DateTime object with the current date and time. Using the Get-Member command, we can see that the output is a System.DateTime object type which has several built-in functions.

Untitled 41
Outputting a DateTime object using the Get-Date cmdlet.

So how would we return a very specific date? We can simply pass in a date and time to have a proper DateTime object returned as seen below.

Get-Date -Date "10/29/2020 12:00:00"
Untitled 42
Outputting a specific date from the Get-Date cmdlet.

Of course, we often want to perform a date calculation from the current time. How would we go about subtracting or adding time to the current date? With the DateTime object type, there are several built-in methods that make this very easy (non-exhaustive list below).

  • AddDays
  • AddHours
  • AddSeconds
  • AddMonths
  • AddYears

To use this, let us show the example of adding two days and five hours to a date. We can chain the AddDays and the Addhours methods onto our date stored in the variable $CurrentDate.

$CurrentDate = Get-Date
$CurrentDate.AddDays(2).AddHours(5)
Untitled 43
Demonstrating adding time using the AddDays and AddHours methods for a DateTime object.

How would we subtract time from a date? All of these methods have “add” in the name and not subtract. To subtract time, we simply need to pass in negative values.

$CurrentDate = Get-Date
$CurrentDate.AddDays(-2).AddHours(-5)
Untitled 44
Demonstrating subtracting time using the AddDays and AddHours methods for the DateTime object.

Formatting Dates and Times

There are two ways to output a specific date-time format. You can use either the -Format parameter or the -UFormat parameter. The latter parameter uses the Unix formatting syntax whereas the former uses .NET formatting syntax. In the below code example we demonstrate an example using both. There are many different formatting identifiers available, and we will not list them all here but can be referenced here.

Get-Date -Format "yyyyMMdd_hhmmss"
Get-Date -UFormat "%Y%m%d_%H%M%S"
Untitled 45
Demonstrate using the same format for both .NET and Unix formatting strings in Get-Date.

Using Get-Culture in Get-Date

Different operating system languages may use different date and time formats. When you use Get-Culture you are able to return a localization object that PowerShell can use to return a localized string. This means that you will have to convert the DateTime object to a string type and pass the localization that you want.

(Get-Date).ToString("dddd, yyyy-MM-dd",(Get-Culture -Name 'en-US'))
(Get-Date).ToString("dddd, yyyy-MM-dd",(Get-Culture -Name 'nl-NL'))
Untitled 46
Demonstrating localization in dates.

As you can see, Thursday is now returned in the Dutch language using the nl-NL encoding.

The DateTime Object Class

Since we know that the Get-Date command outputs a DateTime object, is there more that we can do with this object? Not that we will go into every method, but there are a few methods that are very useful to use. The following are a handful of functions that are available for use with an existing DateTime objects.

  • IsDaylightSavingTime
  • ToFileTime and ToFileTimeUTC
  • ToUniversalTime
([DateTime]"10/20/2020").IsDaylightSavingTime()
([DateTime]"10/20/2020").ToFileTime()
([DateTime]"10/20/2020").ToFileTimeUtc()
([DateTime]"10/20/2020").ToUniversalTime()
Untitled 47
Demonstrating additional useful DateTime object methods.

There are a handful of static functions that are very useful as well. These can be used without a declared DateTime object.

  • DaysInMonth
  • Parse and ParseExact

The first method simply returns the number of days in any given month when passed a year and month number. Parse attempts to create a DateTime object out of a given string using common formats. What if the string you are passing in doesn’t fit any known format? You can use ParseExact to do so by giving a date and time template to follow.

[DateTime]::DaysInMonth(2020, 10)
[DateTime]::Parse("10/10/2020")
[DateTime]::ParseExact("10 10 2020","MM dd yyyy", $Null)
Untitled 48
Demonstrating DateTime static functions.

The date 10 10 2020 is not one that the .NET parser knows about as spaces are not typically used as separators. Therefore, we pass in the template MM dd yyyy which informs the parser how to look at the string and properly return a DateTime object.

TimeSpans

Finally, we are going to quickly touch on TimeSpan objects. This is not technically a date and time, but rather a span of time between two given points. You can pass in a number of different times in to generate a timespan object that includes the given interval using the New-TimeSpan cmdlet. You can also combine this with Get-Date to specify a start and end date (if no start is given, the current date and time is used), then you can determine the number of days until that point.

New-TimeSpan -Days 30
New-TimeSpan -End (Get-Date "12/31/2020")
Untitled 49
Demonstrating DateTime static functions.

Conclusion

There are many ways to work with dates and times in PowerShell and there are even more methods and techniques that can take your script writing to the next level. Leverage the extensive power of Get-Date, New-TimeSpan, and the DateTime object to create advanced scripts that handle dates and times with ease.