Using the New-Timespan Cmdlet

Performing Date Arithmetic

The New-TimeSpan cmdlet provides a way to do date arithmetic within Windows PowerShell. For example, this command tells you the number of days between today’s date and New Year’s Eve 2006:

New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2006)

When this command was run on May 10, 2006 we got back the following:

Days              : 235
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 203040000000000
TotalDays         : 235
TotalHours        : 5640
TotalMinutes      : 338400
TotalSeconds      : 20304000
TotalMilliseconds : 20304000000

Note. All those who knew that there were 20,304,000,000 milliseconds between May 10, 2006 and December 31, 2006 please raise your hands.

To use New-TimeSpan you just need to pass it a pair of date-time values. The best way to do that is to use the Get-Date method; that helps ensure that you get a pair of date-time objects that New-TimeSpan can work with. For our first date, we simply use the Get-Date cmdlet without any additional parameters (note that the cmdlet must be enclosed in parentheses):


For our second date we also call Get-Date, but we tacked on the -month, -day, and -year parameters, along with the appropriate values:

New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2006)

What if you need to know how long it is until a more specific time, such as 11:30 PM on December 31st? As usual, no problem: just include the -hour and the -minute parameters along with the appropriate values (for the hours, use the 24-hour time format). In other words:

New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2006 -hour 23 -minute 30)