Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for inclusion of a datetime in a range in Rails?

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?

like image 531
sirdharma Avatar asked Oct 26 '25 06:10

sirdharma


1 Answers

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

like image 199
Brian Avatar answered Oct 28 '25 03:10

Brian