简体   繁体   中英

How can I find records from today, yesterday and so on with Ruby on Rails?

I want to find all records, say Posts, created today with Ruby on Rails, then all Posts created yesterday, and so on… how should I do?

Thank you,

Kevin

Try this:

#Today
Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 })
#Yesterday
Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today })

Or this (preferable, in my opinion):

#Today
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today] )
#Yesterday
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today - 1] )

As a rule I store all dates on my server in UTC timezone and let the UI handle any timezone conversion. To get the sort of query you are after to work correctly I had to massage the incoming date into a UTC specific time range first.

require 'date'

class Post < ActiveRecord::Base

  def self.created(a_date)
    return Post.where(created_at: to_timerange(a_date))
  end

  private

  def self.to_timerange(a_date)
    raise ArgumentError, "expected 'a_date' to be a Date" unless a_date.is_a? Date
    dts = Time.new(a_date.year, a_date.month, a_date.day, 0, 0, 0).utc
    dte = dts + (24 * 60 * 60) - 1
    return (dts...dte)
  end

end

This then allows you to call

# today
posts = Post.created(Date.today)
# yesterday
posts = Post.created(Date.today - 1)

To query using a range I prefer the following:

yesterday = Date.yesterday
start = yesterday.beginning_of_day
#Fri, 27 Nov 2020 00:00:00 UTC +00:00
end = yesterday.end_of_day
# Fri, 27 Nov 2020 23:59:59 UTC +00:00 - the value here is one second before midnight
# meaning we should use an inclusive range using two dots:
range = start..end

Post.where(created_at: range)

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