37
votes

I have a table of deals and need to find records where the date matches today's date.

From the rails console, the date field I need to match looks like this. I've assigned a record to deal for testing.

ruby-1.9.2-p0 > deal.start
=> Tue, 10 May 2011 00:00:00 UTC +00:00 

If I try to find any records matching the start date with today like this I get nil

ruby-1.9.2-p0 > Deal.find_by_start(Date.today)
=> nil

then I thought I could match by converting Date.today to a datetime.

ruby-1.9.2-p0 > Date.today.to_datetime
=> Tue, 10 May 2011 00:00:00 +0000 
ruby-1.9.2-p0 > Deal.find_by_start(Date.today.to_datetime)
=> nil

How can I get this to work? I'm using Rails 3.

Edit: I thought about converting them both to a consistent format which will works but not when trying to using the find_by_start method

ruby-1.9.2-p0 > deal.start.strftime("%a, %e %B %Y") == Date.today.strftime("%a, %e %B %Y")
=> true 

ruby-1.9.2-p0 > Deal.find_by_start.strftime("%a, %e %B %Y") == Date.today.strftime("%a, %e %B %Y")
NoMethodError: undefined method `strftime' for nil:NilClass
3

3 Answers

65
votes

Rails 5.1 has introduced Date#all_day helper, which returns a range object for a given date, so you can just write:

Deal.where(start: Date.today.all_day)

You can also use SQL DATE() function for your goal, e.g.:

@deals = Deal.where('DATE(start) = ?', Date.today)
54
votes

Keep in mind a DateTime holds a date and a time, so you're looking for records that have a precise value, not just the same day.

You can do this one of two ways. You can either select the range of time from the beginning of the day to the end, or you can create a date column to help group your data better.

The range version looks like this:

@deals = Deal.where('start BETWEEN ? AND ?', DateTime.now.beginning_of_day, DateTime.now.end_of_day).all

The other one requires creating a new start_date column in your table and populating it with the dates accordingly. You can index this date and have your queries run much faster, as range selections aren't always quick on large sets of data.

10
votes

For those still on Rails 4:

To augment not_a_patch's answer above, I would use:

Deal.where(start: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)

because Time.zone will use UTC (which is how your date time field is stored) while DateTime.now will not.

> DateTime.now
=> Fri, 08 Sep 2017 11:28:21 -0400
> Time.zone.now
=> Fri, 08 Sep 2017 15:29:53 UTC +00:00