Getting difference per day from two dates in Powershell
I am trying to get the difference of days in Windows powershell, I am extracting the last date of the year i.e. 20171231 (yyyyMMdd) from a text file that I have saved locally in this file.
Here is the code below that I am trying but cannot get the difference in days, I get the wrong output by subtracting directly, if I convert the string extracted from the file and then subtract it with the date type, even then I get 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
source to share
Use New-TimeSpan
how it represents a time interval . Thus,
$d1 = '2017-01-01'
$d2 = '2017-05-01'
$ts = New-TimeSpan -Start $d1 -End $d2
$ts.Days # Check results
120
source to share
$ DateStr will be a string, so it cannot 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
source to share
Great answers from others, but I use the function a lot Date-Diff
(it's powerful and well known to developers). See example below:
Using Namespace Microsoft.VisualBasic
Add-Type -AssemblyName Microsoft.VisualBasic
$beg = Get-Date '2019-01-01'
$end = Get-Date
[DateAndTime]::DateDiff([DateInterval]::Day, $beg, $end)
NTN
source to share