Reputation: 711
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
Upvotes: 31
Views: 102598
Reputation: 7327
Explaination
We can use floor or ceiling to get the full number of days between two dates, if you want to round it up or down use [math]::Round instead.
Example:
As a Positive Value:
$pastDate = (Get-Date).AddDays(-44.9)
[math]::Floor(((Get-Date) - $pastDate).TotalDays)
44
As a Negative Value:
$pastDate = (Get-Date).AddDays(-44.9)
[math]::Ceiling(($pastDate-(Get-Date)).TotalDays)
-44
Upvotes: 1
Reputation: 1480
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 $start = Get-Date '2019-01-01' #Convert string into Date type. $end = Get-Date [DateAndTime]::DateDiff([DateInterval]::Day, $start, $end)
Edit: Apparently, the new version of PowerShell will support .NET 7, in which case, you won't need to even add assembly.
HTH
Upvotes: 2
Reputation: 27428
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
Upvotes: 1
Reputation: 91
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)
Upvotes: 9
Reputation: 17462
$Date = Get-Date
$diff = Get-Content C:\Users\Date.txt -raw
#Convert it to the date type
$diff = [datetime]::parseexact($diff, 'yyyyMMdd', $null)
#simply difference between dates give you a timespan, take days
($diff - $Date).Day
Upvotes: 0
Reputation: 31
$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
Upvotes: 2
Reputation: 24071
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
Upvotes: 69