Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

range

ruby

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?

like image 612
Landitus Avatar asked Dec 23 '10 19:12

Landitus


People also ask

How do you find a date within a range in Excel?

Use VLOOKUP to search date in date ranges and return value on the same row.

How do you calculate date range?

To count numbers or dates that fall within a range (such as greater than 9000 and at the same time less than 22500), you can use the COUNTIFS function. Alternately, you can use SUMPRODUCT too.

How do you check if a date is in a range Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.


2 Answers

In Ruby 1.9.2 === doesn't work, I get an error:

irb(main):019:0> (Time.now .. (Time.now+1)) === Time.now TypeError: can't iterate from Time     from (irb):19:in `each'     from (irb):19:in `include?'     from (irb):19:in `include?'     from (irb):19:in `==='     from (irb):19     from /opt/ruby192/bin/irb:12:in `<main>' 

Instead use #cover?:

irb(main):002:0> (Time.now..Time.now+4).cover?(Time.now) => true irb(main):003:0> (Time.now..Time.now+4).cover?(Time.now+10) => false 
like image 119
heathd Avatar answered Sep 19 '22 06:09

heathd


Use ===


Actually, there is an operator that will do this. Make a Range and compare Time objects to it using the === operator.

start   = Time.now.to_i  range   = start..(start + 2) inside  = start + 1 outside = start + 3        # ok, now...  range === inside  # true range === outside # false 


Update post-comment-flood: This version works well everywhere. (In Rails, in Ruby 1, and in Ruby 2.) The earlier irb example also worked fine but the interactive example wasn't always reproduced correctly in some experiments. This one is easier to cut-and-paste.

It's all straightened out now.

like image 21
DigitalRoss Avatar answered Sep 22 '22 06:09

DigitalRoss