Creating Time Spans

by Dec 16, 2016

You can use New-TimeSpan to define “amounts” of time, and then add or subtract them from dates. Here is an example:

$1Day = New-TimeSpan -Days 1
$today = Get-Date
$yesterday = $today - $1Day

$yesterday

A much easier way uses the built-in methods for DateTime objects:

$today = Get-Date
$yesterday = $today.AddDays(-1)

$yesterday

Also, you can use the TimeSpan .NET type to create time span objects:

 
PS C:\> [Timespan]::FromDays(1)


Days              : 1
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 864000000000
TotalDays         : 1
TotalHours        : 24
TotalMinutes      : 1440
TotalSeconds      : 86400
TotalMilliseconds : 86400000
 

Twitter This Tip! ReTweet this Tip!