使用带有日期时间范围的Ruby Range#include?
会引发异常:
> (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).include?(Time.zone.now)
TypeError: can't iterate from ActiveSupport::TimeWithZone
使用Rails' Range#overlaps?
有效:
> (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).overlaps?(Time.zone.now..Time.zone.now)
=> true
我不喜欢这样一个事实:我必须创建一个单元素范围以使用overlaps?
检查包含是否有办法在Rails中使用include?
和日期时间范围?
答案 0 :(得分:1)
啊哈!
这是怎么回事?
Time.zone.now.between?(Time.zone.now.beginning_of_day,Time.zone.now.end_of_day)
结果:
2.3.0 :001 > Time.zone.now.between?(Time.zone.now.beginning_of_day,Time.zone.tomorrow.end_of_day)
=> true
2.3.0 :002 > Time.zone.tomorrow.between?(Time.zone.now.beginning_of_day,Time.zone.now.end_of_day)
=> false
2.3.0 :003 > Time.zone.yesterday.between?(Time.zone.now.beginning_of_day,Time.zone.now.end_of_day)
参考:http://apidock.com/rails/ActiveSupport/TimeWithZone/between%3F