简体   繁体   中英

Comparing a Date to the Datetime Created_at in rails3

So I'm trying to do things like so:

today = Date.today - 1
todaysReport = Report.where(:created_at => today).find_by_user_id(user.id)

The problem is created_at is a datetime, so it won't find any matches..Any suggestions?

You probably want something like this:

yesterday = Time.now - 1.day
user = User.find(user_id)

todaysReport = user.reports.where(["created_at >= ? AND created_at <= ?", yesterday.beginning_of_day, yesterday.end_of_day])

In postgres, you can cast a timestamp as a date. For example:

Report.where("created_at::date =?", Date.today - 1)

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

You need to compare against a range from one midnight to the next. Also, this is a good candidate for making your own class method for higher flexibility.

class Report
  # All reports created on the specified Date
  def self.created_on(date)
    where(['created_at >= ? AND created_at < ?', date, date + 1])
  end
end

# Find all reports created yesterday by our user
Report.created_on(Date.today - 1).where(:user_id => user.id)

In Rails 5.1 and greater, you can use all_day instance method like this:

today = Date.today - 1
todaysReport = Report.where(created_at: today.all_day).find_by_user_id(user.id)

It can also be TimeWithZone if time zone specified in application config. To get Date to TimeWithZone you have to do like Date.today.to_time.in_time_zone.

Have you tried using #to_datetime , which Rails adds to the Date and Time classes?

Report.where(:created_at => today.to_datetime).find_by_user_id(user.id)

Actually surprised AR doesn't handle this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM