Roman
Roman

Reputation: 10403

What is the correct way to compare times in Ruby?

The following example is confusing me. Why does the comparison return false?

require 'active_support/time'

time1 = Time.new.utc.end_of_day  # 2013-01-09 23:59:59 UTC
time2 = Time.parse(time1.to_s)   # 2013-01-09 23:59:59 UTC

time1 == time2                   # false
time1.eql?(time2)                # false 
time1.equal?(time2)              # false

What am I doing wrong?

Upvotes: 0

Views: 385

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

time2 is generated from a string representation of time1 which lacks information. Namely, the microseconds.

require 'active_support/time'

time1 = Time.new.utc.end_of_day  # => 2013-01-09 23:59:59 UTC
time2 = Time.parse(time1.to_s)   # => 2013-01-09 23:59:59 UTC

time1.usec # => 999999
time2.usec # => 0

Workaround:

If you don't need microsecond precision, you can round both timestamps to seconds.

time1.to_i == time2.to_i # => true

Upvotes: 1

Related Questions