How to know if today's date is in a date range

2019-01-20 22:48发布

I have an event with start_time and end_time and want to check if the event is "in progress". That would be to check if today's date is in the range between the two dates.

How would you do this in a function?

标签: ruby date range
8条回答
劫难
2楼-- · 2019-01-20 23:13

If you are using Rails, you could try this:

ruby-1.8.7-p299 :015 > a = DateTime.now
 => Fri, 02 Dec 2011 11:04:24 -0800 
ruby-1.8.7-p299 :016 > (a.beginning_of_day..a.end_of_day).include_with_range? a
 => true 
ruby-1.8.7-p299 :017 > (a.beginning_of_day..a.end_of_day).include_with_range? a+10.days
 => false 
ruby-1.8.7-p299 :018 > (a.beginning_of_day..a.end_of_day).include_with_range? a+25.hours
 => false 
ruby-1.8.7-p299 :019 > (a.beginning_of_day..a.end_of_day).include_with_range? a+2.hours
 => true 

Note: I just used beginning_of_day and end_of_day to provide an easy range. The important part is the include_with_range? method on a Range.

查看更多
神经病院院长
3楼-- · 2019-01-20 23:14

If they're timestamps:

def in_progress?
  (start_time..end_time).include?(Time.now)
end
查看更多
登录 后发表回答