Using Ruby's Range#include? with a datetime range throws an exception:
> (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).include?(Time.zone.now)
TypeError: can't iterate from ActiveSupport::TimeWithZone
While using Rails' Range#overlaps? works:
> (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).overlaps?(Time.zone.now..Time.zone.now)
=> true
I dislike the fact that I have to create a single-element range to check for inclusion using overlaps? Is there a way to use include? with a datetime range in Rails?
Aha!
How is this?
Time.zone.now.between?(Time.zone.now.beginning_of_day,Time.zone.now.end_of_day)
Result:
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)
Reference: http://apidock.com/rails/ActiveSupport/TimeWithZone/between%3F
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With