Getting the no of days difference from the two dates in Powershell

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

$DateStr is going to be a string, so it can't be parsed as a date. You can also use new-timespan to get the difference between two dates.

$Date = Get-Date

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

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

$diff3 = New-TimeSpan -Start $diff -end $Date

#Number of days
$diff3.days

Tags:

Powershell