Using Powershell to Compare the Difference Between Dates

Following up on the last post about dates and using Get-Date we look at the difference between dates and how to compare or calculate them. Dates can be tricky because you are counting on the system to do the calculation correctly but this requires passing the right info or string.

Get Difference Between Two Dates

First we use our trusty Get-Date Cmdlet to get today and then we need another date to compare. Normally this is presented as a string so I am casting the string using the Datetime datatype. in this case we should get a date variable with a time set to midnight.

Keep your eye on the parenthesis, they are important here.

([datetime]'2051-3-21').Date   ## cast as datetime and sets the time to midnight
(Get-Date).Date    ## today's date set to midnight

([datetime]'2051-3-21').Date - (Get-Date).Date   ## returns object and calculations

Reversing For Positive or Negative Numbers

(Get-Date).Date - ([datetime]'2051-3-21').Date  ##  negative 
([datetime]'2051-3-21').Date - (Get-Date).Date   ## positive

Using A Variable

Your script may require this value to be called a other points so you can create the object and call it back (db tales com) at anytime to get the Days, Hours, Minutes, Seconds and more…

$diff = ([datetime]'2051-3-21').Date - (Get-Date).Date

$diff.TotalDays
$diff.TotalHours
$diff.TotalMinutes
$diff.TotalSeconds
$diff.TotalMilliseconds

Using the New-Timespan Cmdlet

Starting around Powershell 5.1 MS created a new Cmdlet to handle the “between dates” called New-Timespan.

New-TimeSpan -End (Get-Date -Year 2056 -Month 7 -Day 9)