0

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.

worldask
  • 1,837
  • 3
  • 22
  • 37
Tolsto
  • 1,418
  • 2
  • 17
  • 45
  • Looks like you might get some hints here [Comparing dates in rails](http://stackoverflow.com/questions/992431/comparing-dates-in-rails) – Robert Christopher Sep 19 '14 at 16:36
  • What's the class of each of your objects? – Max Williams Sep 19 '14 at 16:40
  • @MaxWilliams It's both a DateTime object. Please see my updated question. – Tolsto Sep 19 '14 at 16:48
  • I was running similar DateTime comparisons in a local console and was able to replicate what you're seeing (and now I'm really curious as to why). However, one thing I was able to do to get the comparisons working correctly was to convert the DateTime objects to integers for the comparison (time1.to_i > time2.to_i). That seemed to get the expected results from the comparison operators but I'm very interested why those two seemingly identical DateTimes did not compare correctly. – craig.kaminsky Sep 19 '14 at 16:57

1 Answers1

1

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.
Community
  • 1
  • 1
Vijay Meena
  • 683
  • 1
  • 7
  • 12