1

This has got to be an easy thing to do, but I think that Rail's timezone implementation is throwing off my work...

How can I create a scope in Rails 3 (and ruby 1.9.2) to query for records created today?

Currently, I'm doing this:

  scope :today, lambda { 
    where("created_at >= ? and created_at <= ?", 
           Date.today.beginning_of_day, Date.today.end_of_day)
  }  

And it doesn't appear to be working as it should. I want "today" to represent the 24 hour period from 12am to 11:59pm for a user's local timezone. Do I need to convert the date to UTC or something?

3 Answers 3

3

You will need to consider user's timezone. That is, beginning of day and end of day in the user's timezone. For that, first parse the current time in user's timezone. You can set the zone to user's timezone and do the calculation or you can parse the time directly using a variation of the following code.

timezone = current_user.timezone # Mountain Time (US & Canada)
users_current_time = ActiveSupport::TimeZone[timezone].parse(Time.now.to_s)

users_current_time.beginning_of_day and users_current_time.end_of_day should generate the right time range (which you app would convert to UTC and fire the query, if UTC is your applications timezone)

If you want to do that with scopes only, then I suggest you set the Time.zone = current_user.timezone before_filter of all actions and use it in the scope. This railscast gives fair idea about how to go about doing that.

1

If you're using mysql, then I think you just want to match on the day, not the time right? Stated another way, you want all records from Dec. 1st. Between 12:00am and 11:59pm on Dec. 1st is implied if you just search on date.

 scope :today, lambda { 
    where("created_at = ?",
           Time.now.strftime("%Y-%d-%m")
  } 

Something like that should work

3
  • Just wondering -- Will that return true for an entire DateTime format? If so, I've been solving this issue with verbose solutions for years. Dec 1, 2010 at 16:54
  • It will return a SQL query like: "... WHERE created_at = '2010-12-01' ... " which MySQL then parses into matching anything on Dec. 1st
    – brycemcd
    Dec 1, 2010 at 17:14
  • strtime format is wrong, should be YEAR-MONTH-DAY, as in "%Y-%m-%d"
    – mguymon
    Nov 12, 2013 at 21:52
0

How about this?

  scope :today, lambda { 
    where("created_at >= ? and created_at <= ?", 
           Date.today.beginning_of_day.utc, Date.today.end_of_day.utc)
  }  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.