powershell

Getting the # of days difference between two dates in Powershell


I am trying to get the number of days difference in Windows powershell, I am extracting the last date of the year i.e.. 20171231(yyyyMMdd) from a text file that I have locally stored the date in that file.

Here is the below code that I am trying but not able to get the difference of the days, am getting the wrong output by directly subtracting, if am converting the string extracted from the file and then subtract it with the date type, even then am getting the wrong output.

$DateStr = (Get-Date).ToString("yyyyMMdd")

$content = Get-Content C:\Users\Date.txt 

$diff = $content.ToString();

#Convert it to the date type
$diff = [datetime]::parseexact($diff, 'yyyyMMdd', $null)

#$diff3 = $diff - $DateStr

Solution

  • Use New-TimeSpan as it represents a time interval. Like so,

    $d1 = '2017-01-01'
    $d2 = '2017-05-01'
    $ts = New-TimeSpan -Start $d1 -End $d2
    $ts.Days # Check results
    120