Datetime comparison in Rails is always false
I am trying to compare two dates for which both are datetime
.
closed_at
and updated_at
(a updated_at
- the one that is already created by the rails)
This is my code:
<% if @task.closed_at == @task.updated_at %>
*Some stuff*
<% end %>
When the task is closed, it is automatically updated.
irb(main):011:0> Task.first.closed_at
=> Fri, 07 Aug 2015 10:47:58 CEST +02:00
irb(main):012:0> Task.first.updated_at
=> Fri, 07 Aug 2015 10:47:58 CEST +02:00
irb(main):013:0> Task.first.closed_at == Task.first.updated_at
=> false
irb(main):014:0> Task.first.closed_at.to_datetime == Task.first.updated_at.to_datetime
=> false
I read these two posts:
comparing datetime and time results in a false result
Comparison to DateTime fails in Rails
But neither the data type is different, nor the time zone.
Environment:
- ruby 2.2.2p95
- rails 4.2.3
- pg 0.18.2
source to share
This can happen because Ruby times are compared to fractions of a second. Thus, the "print" may look the same, but there is a time difference between both dates.
Try using the to_f method to see the difference between @ task.closed_at and @ task.updated_at. Pretty sure about that.
To solve your problem, just ignore the millisecond portion of dates:
<% if @task.closed_at.to_i == @task.updated_at.to_i %>
*Some stuff*
<% end %>
source to share
Try this little experiment with any model that has a created_ad and an updated_ad:
user = User.new
user.created_at = 'Fri, 07 Aug 2015 10:47:58 CEST +02:00'.to_datetime
user.updated_at = 'Fri, 07 Aug 2015 10:47:58 CEST +02:00'.to_datetime
user.created_at == user.updated_at
The last statement above returns true
. So there must be a time difference that is not displayed when the time is displayed.
source to share
This is due to the small difference (in milliseconds) between the two variables. There is one blog post in this article:
http://railsware.com/blog/2014/04/01/time-comparison-in-ruby/
Basically, a simple solution would be to convert the time values to int:
<% if @task.closed_at.to_i == @task.updated_at.to_i %>
*Some stuff*
<% end %>
source to share