Ruby on rails Rails where()和时区

Ruby on rails Rails where()和时区,ruby-on-rails,activerecord,timezone,rails-activerecord,Ruby On Rails,Activerecord,Timezone,Rails Activerecord,我正在尝试使用以下方法查找“条目”创建日期(在我当前的时区): Entry.where("DATE(created_at) = DATE(?) AND email = ?", Time.now, email) Time。现在给了我当前区域的时间,但查询似乎是在搜索每个条目的创建时间列的UTC时间 你知道如何在服务器的时区中找到今天创建的条目吗 使用?立即使用时区。这将使用一个ActiveSupport::TimeWithZone对象,当在数据库搜索中使用该对象时,该对象将自动转换为UTC。一旦

我正在尝试使用以下方法查找“条目”创建日期(在我当前的时区):

Entry.where("DATE(created_at) = DATE(?) AND email = ?", Time.now, email)
Time。现在
给了我当前区域的时间,但查询似乎是在搜索每个条目的创建时间列的UTC时间


你知道如何在服务器的时区中找到今天创建的条目吗

使用?

立即使用
时区。这将使用一个
ActiveSupport::TimeWithZone
对象,当在数据库搜索中使用该对象时,该对象将自动转换为UTC。

一旦在SQL中调用该函数,您就会失去对时区信息的跟踪。有两件事需要记住:

  • 数据库中的所有内容都将以UTC为单位,并且所有内容都包括
    DATE()
    的结果
  • 本地时区中的一个日期(即天)可以轻松跨越UTC中的两个日期,因此您需要查看整个时间戳(在两侧),而不仅仅是(UTC)日期组件
  • 像这样的方法应该会奏效:

    now = Time.now
    Entry.where('created_at between :start and :end and email = :email',
        :start => now.beginning_of_day,
        :end   => now.end_of_day,
        :email => email
    )
    
    时间应自动转换为UTC。您可能希望以稍微不同的方式处理上限;使用
    end\u of_day
    可以为您提供
    23:59:59
    ,这样您就有了一个小空间,可以让您想要捕获的东西溜过去。您可以使用显式的半开区间(而不是SQL的
    between
    使用的闭合区间)来解决该问题,如下所示:

    now = Time.now
    Entry.where('created_at >= :start and created_at < :end and email = :email',
        :start => now.beginning_of_day,
        :end   => now.tomorrow.beginning_of_day,
        :email => email
    )
    
    now=Time.now
    条目.where('created_at>=:start和created_at<:end和email=:email',
    :start=>now.开始一天的工作,
    :end=>现在。明天。一天的开始,
    :email=>email
    )
    
    首先,您应该获得时区,然后是时区偏移量。 例如,当前时区是

    美国/洛杉矶

    时区偏移查找:

     Time.now.in_time_zone(current_time_zone).utc_offset / 3600) * -1
    
    七,

    在控制器中:

     start_date_format = DateTime.strptime(@start_date, date_format)
     start_date_format_with_hour = 
     DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
    
     end_date_format = DateTime.strptime(@end_date, date_format)
     end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
    
     @filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour
    
    start\u date\u format=DateTime.strtime(@start\u date,date\u format)
    开始日期格式为小时=
    DateTime.strTime((开始日期格式到+时区偏移量*60*60)。到秒,'%s')。strftime(日期格式)
    end_date_format=DateTime.strtime(@end_date,date_format)
    结束日期格式,时间=DateTime.strTime((结束日期格式到+时区偏移量*60*60)。结束时间,'%s')。strftime(日期格式)
    @筛选\u date=“invoices.created\u at>=”和invoices.created\u at<?”,开始\u date\u format\u为小时,结束\u date\u format\u为小时
    
    我想到了这一点,但它会根据UTC的24小时跨度而不是本地返回条目。对吗?这似乎与使用Time.now和Time.now.utc具有相同的效果。看起来查询是用UTC时间构建的,但这会在一天内为我提供英格兰的条目,而不是我所在的地方。