PowerTip: Get Time Difference between Dates with PowerShell

PowerTip: Get Time Difference between Dates with PowerShell

  • Comments 13
  • Likes

Summary: Use New-TimeSpan to produce the time difference between two dates.

Hey, Scripting Guy! Question I know I can subtract dates, but is there a Windows PoweShell cmdlet to show me the time difference between dates?

Hey, Scripting Guy! Answer Use New-TimeSpan and supply the information!
          For example, to show the difference between today and the upcoming New Year:


$EndDate=[datetime]”01/01/2014 00:00”

NEW-TIMESPAN –Start $StartDate –End $EndDate

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Very much required for all the administrators!!!

  • Nice Article.

  • Why not just subtract the dates and let PowerShell do the conversion for you? The results are the same just a little less explicit. PS >($EndDate - $StartDate).gettype().Name TimeSpan

  • @Greg Wohan You are correct. There are two ways in PowerShell to do the same exact thing. Neither is wrong. One uses a Cmdlet and one uses Math (Although I suspect the Cmdlet is just coughing in the math). Choose whichever makes more sense for you to do :) Sean

  • $StartDate is not needed here: PS will use current date for either of two parameters, if it's not explicitly specified. So New-TimeSpan -End 1-Jan-2014 would probably do. ;)

  • Please use day-numbers above 12 in examples, to prevent confusion between day and month position.