从Powershell中的两个日期获得天数差异

时间:2017-05-24 07:16:58

标签: powershell

我试图在Windows PowerShell中获得天数差异,我正在从我在本地存储该文件中的日期的文本文件中提取一年中的最后一个日期,即20171231(yyyyMMdd)。

以下是我正在尝试但不能得到天数差异的代码,通过直接减去得到错误的输出,如果转换从文件中提取的字符串然后用日期类型减去它,即便如此,我的输出也是错误的。

$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

5 个答案:

答案 0 :(得分:15)

New-TimeSpan用作it represents a time interval。像这样,

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

答案 1 :(得分:2)

$ DateStr将是一个字符串,因此无法将其解析为日期。您还可以使用new-timespan来获取两个日期之间的差异。

$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

答案 2 :(得分:0)

$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

答案 3 :(得分:0)

其他人的答案很不错,但我经常使用Date-Diff函数(该函数功能强大,开发人员众所周知)。请参见下面的示例:

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

答案 4 :(得分:0)

一个快速、肮脏、单行的 powershell 脚本,用于获取当前日期和任何未来日期之间的差异:

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