Tolsto
Tolsto

Reputation: 1428

Compare datetime objects in Rails

I'm trying to compare two DateTime objects. However, I don't quite understand the result.

DateTime.parse("2014-09-14 01:12:03 +0200")
>> Sun, 14 Sep 2014 01:12:03 +0200   

Foo.order("created_at").last.created_at.to_datetime
>> Sun, 14 Sep 2014 01:12:03 +0200

But

Foo.order("created_at").last.created_at.to_datetime === DateTime.parse("2014-09-14 01:12:03 +0200")
true

Foo.order("created_at").last.created_at.to_datetime > DateTime.parse("2014-09-14 01:12:03 +0200")
true

Why is the result of the > comparison not false? (Rails 4.0.9)

Edit: I got it working using the === operator. But it still returns true when I use the > operator.

Upvotes: 0

Views: 2270

Answers (1)

Vijay Meena
Vijay Meena

Reputation: 695

Operator === is defined in Date class in Ruby which is parent class of DateTime. Operator === Returns true if they are the same day which is the case in your example. See description

Now to answer other part of your question about comparing two DateTime, see this answer. Which states that the act of saving and reloading datetime in database truncates the seconds_fraction part of the DateTime.

You can verify that in your rails console by below code -

obj1 = Foo.order("created_at").last.created_at.to_datetime
obj2 = DateTime.parse("2014-09-14 01:12:03 +0200")

obj1.sec > obj2.sec #comparing seconds, returns false. Both equal
obj1.sec_fraction > obj2.sec_fraction #should return true. Not equal.

Upvotes: 1

Related Questions