【问题标题】:Two identical datetimes not comparing equal两个相同的日期时间不相等
【发布时间】:2015-05-11 20:42:02
【问题描述】:

据我所知,我有两个相同的日期。

$theDate = (Get-Date -Hour 0 -Minute 00 -Second 00)
$otherDate = (Get-Date -Hour 0 -Minute 00 -Second 00)

按此顺序执行

这两个都显示为Monday, May 11, 2015 12:00:00 AM,但是当我这样做($theDate -eq $otherDate) 时,它返回false。我试过$theDate.equals($otherDate)(($theDate) -eq ($otherDate)) 一样的东西。 我唯一能返回 true 的是($theDate -gt $otherDate) 我是疯了还是菜鸟?

【问题讨论】:

  • 您可以做的一件事是$theDate = (Get-Date).Date。这使用了this property,它返回一个只有日期部分和一个 0'd 时间部分的 DateTime。
  • 只是一个提示 - 如果您想查看 DateTime 的“确切”值,请尝试查看其 Ticks 属性。

标签: powershell datetime date-comparison


【解决方案1】:

您忘记了毫秒字段,这对于两个日期时间会有所不同:

PS > $theDate = (Get-Date -Hour 0 -Minute 00 -Second 00)
PS > $otherDate = (Get-Date -Hour 0 -Minute 00 -Second 00)
PS > $theDate.Millisecond
122  
PS > $otherDate.Millisecond
280

将这些字段设置为相同的值可以解决问题:

PS > $theDate = (Get-Date -Hour 0 -Minute 00 -Second 00 -Millisecond 000)
PS > $otherDate = (Get-Date -Hour 0 -Minute 00 -Second 00 -Millisecond 000)
PS > $theDate -eq $otherDate
True

虽然将两个变量分配给同一个日期时间可能更容易:

PS > $theDate = (Get-Date -Hour 0 -Minute 00 -Second 00) 
PS > $otherDate = $theDate
PS > $theDate -eq $otherDate
True

【讨论】:

  • 有趣的是,虽然DateTime 精确到Tick (100ns),但设置-Millisecond 00 也会将亚毫秒部分归零。
  • 或者,用户Get-Date 使用格式化的Get-Date,例如Get-Date (Get-Date -f "MM/dd/yyyy"),它将准确地为您提供当天的午夜。将其转换为 [datetime] 对象(例如 [datetime](get-date -f 'MM/dd/yyyy'))也是如此。这么多选择!
  • @TheMadTechnician (Get-Date).Date.TimeOfDay 将是另一种选择。
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2011-08-03
  • 1970-01-01
相关资源
最近更新 更多