是否可以使用用户指定的time_zone查询特定日期的记录?

时间:2016-03-26 20:34:40

标签: ruby-on-rails postgresql

我正在为每个用户设置全局时区,如下所示:

around_filter :user_time_zone, :if => :current_user

def user_time_zone(&block)
    Time.use_zone(current_user.time_zone, &block)
end

我正在创建一些记录,当我检查它们时,created_at字段似乎使用了正确的time_zone,例如“Caracas”时区:

[#<TimeEntry:0x007f6658ed4e58
  id: "89c12856-4180-41ba-be4c-e1d555cd4b5c",
  description: "New timer",
  created_at: Fri, 25 Mar 2016 11:51:43 VET -04:30,
  updated_at: Fri, 25 Mar 2016 11:51:54 VET -04:30>,
 #<TimeEntry:0x007f6658ed4d18
  id: "8d8598e1-910d-4d89-898e-3de3cdf021c1",
  description: "Connecting the timer hours with projects",
  created_at: Fri, 25 Mar 2016 12:30:11 VET -04:30,
  updated_at: Fri, 25 Mar 2016 12:30:11 VET -04:30>,
 #<TimeEntry:0x007f6658ed4bd8
  id: "29e67663-e538-41e3-ba4e-0d02d3431abc",
  description: "Test completing 2 hours",
  created_at: Fri, 25 Mar 2016 12:30:47 VET -04:30,
  updated_at: Fri, 25 Mar 2016 12:31:08 VET -04:30>,
 #<TimeEntry:0x007f6658ed4a98
  id: "2260c971-c4e0-4ae0-97df-672cdeeac65a",
  description: "Working on project details",
  created_at: Fri, 25 Mar 2016 12:50:55 VET -04:30,
  updated_at: Fri, 25 Mar 2016 12:50:55 VET -04:30>,
 #<TimeEntry:0x007f6658ed4958
  id: "bfe5189d-5124-47c9-ba6d-2f28a08e6c5f",
  description: "Working",
  created_at: Fri, 25 Mar 2016 19:44:07 VET -04:30,
  updated_at: Fri, 25 Mar 2016 19:44:22 VET -04:30>,
 #<TimeEntry:0x007f6658ed4818
  id: "23b3fd5d-8be4-40b7-a9b9-d48e1fe6816d",
  description: "New timer",
  created_at: Sat, 26 Mar 2016 19:51:10 VET -04:30,
  updated_at: Sat, 26 Mar 2016 19:51:41 VET -04:30>]

“2016-03-25”有5条记录,“2016-03-26”有1条记录。我想这样在白天拿它们:

day = '2016-03-25'
@project.time_entries.where("date_trunc('day', created_at) = ?", day).count

然而,我得到了错误的结果,我在25日获得了4条记录,在第26条获得了1条记录,在第27条获得了1条记录。看起来created_at字段使用的是默认的time_zone(这是UTC,并且我正在测试的时间偏差为'+4:30')。

如何使用我设置的time_zone获取特定日期的记录?

1 个答案:

答案 0 :(得分:0)

我设法让它像这样工作,而不是使用字符串条件,我使用范围条件:

total_time = @project.time_entries.where(created_at: (day.beginning_of_day..day.end_of_day)).count