PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Working With TimeSpan Objects

TimeSpan objects represent a given amount of time. They are incredibly useful when you calculate with dates or times because they can represent the amount of time between two dates, or can add a day (or a minute) to a date to create relative dates.

Here are some samples to get you started:

# get a timespan representing one day and 3 hours:
New-TimeSpan -Days 1 -Hours 3

# get a timespan representing the time difference between now and next Christmas
New-Timespan -End '2013-12-24 18:30:00'

# get a timespan by subtracting two dates:
[DateTime]'2013-12-24 18:30:00'  - (Get-Date) 

# get a timespan by subtracting a timespan representing one day from a date:
(Get-Date) - [TimeSpan]'1.00:00:00'

# getting a specific property from a timespan (for example just the days):
$days = (New-Timespan -End '2013-12-24 18:30:00').Days
"Days to Christmas: $days"

# negating a timespan:
$timespan = New-TimeSpan -Days 1
$timespan.Negate()
$timespan

# creating a negative timespan directly:
New-TimeSpan -Days -1

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.