user31792
user31792

Reputation: 43

Two identical datetimes not comparing equal

I have two dates that are identical as far as I can tell.

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

Executed in that order

Both of these show up as Monday, May 11, 2015 12:00:00 AM, but when I do ($theDate -eq $otherDate) it returns false. I've tried $theDate.equals($otherDate) and (($theDate) -eq ($otherDate)) same thing. The only thing I can get to return true is ($theDate -gt $otherDate) Am I crazy or just a noob?

Upvotes: 4

Views: 1155

Answers (1)

user2555451
user2555451

Reputation:

You are forgetting about the millisecond field, which will be different for the two datetimes:

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

Setting these fields to the same value fixes the problem:

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

Although it might be easier to just assign the two variables to the same datetime:

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

Upvotes: 10

Related Questions