Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用RubyonRails如何查找今天、昨天等的记录?_Ruby On Rails_Datetime_Activerecord_Date - Fatal编程技术网

Ruby on rails 使用RubyonRails如何查找今天、昨天等的记录?

Ruby on rails 使用RubyonRails如何查找今天、昨天等的记录?,ruby-on-rails,datetime,activerecord,date,Ruby On Rails,Datetime,Activerecord,Date,我想找到所有记录,比如今天用RubyonRails创建的帖子,然后是昨天创建的所有帖子,等等……我该怎么做 谢谢, 凯文试试这个: #Today Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 }) #Yesterday Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today }) 或者这个(

我想找到所有记录,比如今天用RubyonRails创建的帖子,然后是昨天创建的所有帖子,等等……我该怎么做

谢谢,

凯文

试试这个:

#Today
Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 })
#Yesterday
Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today })
或者这个(在我看来更可取):


通常,我将服务器上的所有日期存储在UTC时区中,并让UI处理任何时区转换。 为了得到您想要的那种查询,以便正确地工作,我必须将传入的日期按摩到 UTC特定时间范围优先

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

要使用范围进行查询,我更喜欢以下选项:

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)

我最近发现Date.today可以等于Date.明天和Date.today可以等于Date.Date,具体取决于时区设置。Date.today使用方框时间(通常是utc)和Date。明天和昨天使用时区,所以要小心。Date.current使用Time.zone并应代替Date.today
# today
posts = Post.created(Date.today)
# yesterday
posts = Post.created(Date.today - 1)
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)