比较日期但不是时代

时间:2015-08-10 16:12:26

标签: date powershell compare

如何比较日期和忽略时间?我有2个相同的日期但不同的时间。我只需要比较日期并忽略时间,但-gt运算符包括时间。这是代码。

if((get-date $Date1) -gt (get-date $Date2))
{
  // do something.
}

1 个答案:

答案 0 :(得分:5)

使用日期时间对象的.Date属性:

if((get-date $Date1).Date -gt (get-date $Date2).Date)
{
  // do something.
}

根据评论:

$date1 = '08/25/2015 00:00:00'
$date2 =  '08/25/2015 12:00:00 AM'

if((get-date $Date1).Date -gt (get-date $Date2).Date)
{
  '$Date1 is greater than $Date2'
}

else { '$Date1 is not greater than $Date2'}

$Date1 is not greater than $Date2

扭转价值观:

$date1 = '08/25/2015 12:00:00'
$date2 =  '08/25/2015 00:00:00 AM'

if((get-date $Date1).Date -gt (get-date $Date2).Date)
{
  '$Date1 is greater than $Date2'
}

else { '$Date1 is not greater than $Date2'}

$Date1 is not greater than $Date2