用相同的数据匹配 Rails end_of_month 到 Time

Match Rails end_of_month to Time with the same data

我试图在依赖于 Rails 的 end_of_month 的 class 上写一个断言,但我无法让它等于新创建的 Time 对象:

Time.new(2014, 12).end_of_month == Time.new(2014, 12, 31, 23, 59, 59)
=> false

两个值 return 来自 to_i 的相同结果:

Time.new(2014, 12).end_of_month.to_i
=> 1420030799
Time.new(2014, 12, 31, 23, 59, 59).to_i
=> 1420030799

但是 to_f 结果略有不同:

Time.new(2014, 12).end_of_month.to_f
=> 1420030800.0
Time.new(2014, 12, 31, 23, 59, 59).to_f
=> 1420030799.0

两个对象都将其 class 报告为 Time。这里发生了什么?我如何创建一个 Time 对象来匹配 end_of_month 编辑的 return?

浮点值不准确

可以通过输出有理值来区分

Time.new(2014, 12, 31, 23, 59, 59).to_r
# => (1420041599/1)

Time.new(2014, 12).end_of_month.to_r
# => (1420041599999999999/1000000000)

来自 Time.to_f 文档

Note that IEEE 754 double is not accurate enough to represent the number of nanoseconds since the Epoch.

来自 Time.to_r 文档

This methods is intended to be used to get an accurate value representing the nanoseconds since the Epoch. You can use this method to convert time to another Epoch.

比较时间时,我通常使用to_i,或者to_f与rspec资产be_within(0.01).of(27.9)