Getting the # of days difference between two dates in Powershell

Viewed 69415

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
6 Answers

A quick, dirty, one line powershell script to get the difference between current date and any future date:

[math]::Ceiling((([DateTime]'mm-dd-yyyy')-(Get-Date)).TotalDays)

Great answers by others but I often use Date-Diff function (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)

HTH

If you convert to datetime objects it's pretty straighforward to subtract them and look at the days property. This works with times too.

[datetime]'9/3' - [datetime]'9/1' | % days

2


[datetime]'10:30' - [datetime]'9:30' | % hours

1
Related