我有一个范围可以查询今天的电话。基于范围,我用它来计算今天的通话量。
我的日期以UTC格式存储,但rails会转换为我当地的时区。我要做的是在今天00:00到23:59之间找到所有电话。
范围:
scope :today, where("DATE(transfer_date) BETWEEN ? AND ?", Time.zone.now.utc.beginning_of_day, Time.zone.now.utc.end_of_day)
irb输出:(由于UTC而捕获的呼叫)
irb(main):010:0> Call.last.transfer_date
Call Load (0.9ms) SELECT "calls".* FROM "calls" ORDER BY "calls"."id" DESC LIMIT 1
=> Sun, 07 Oct 2012 19:45:00 CDT -05:00
irb(main):011:0>
irb(main):011:0> Call.last.transfer_date.utc
Call Load (1.3ms) SELECT "calls".* FROM "calls" ORDER BY "calls"."id" DESC LIMIT 1
=> 2012-10-08 00:45:00 UTC
我正试图弄清楚如何只查询今天00:00到23:59之间的通话。到目前为止尝试使用和不使用utc,zone等的范围都不起作用。它一直根据UTC提取范围,其中包括昨天的呼叫(昨天如果用当地时区格式化的话)。
如何在两次之间进行查询以获得正确的输出?我有点迷失在这里。
答案 0 :(得分:17)
您可以使用专属范围。
scope :today, where(:transfer_date => Date.today...Date.tomorrow)
答案 1 :(得分:7)
我能够通过重写我的范围来补偿UTC,如下所示:
scope :today, where("transfer_date BETWEEN ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)
答案 2 :(得分:0)
也许这有点矫枉过正,但我建议使用辅助方法来获取时间范围,然后查询数据库。像
这样的东西# Gets time range for x number timeunits ago
def time_range(unit, timeunit = nil)
if timeunit == "weeks"
now = Time.zone.now.beginning_of_week
elsif timeunit == "months"
now = Time.zone.now.beginning_of_month
else
now = Time.zone.now.beginning_of_day
end
# Ex: time_range(0, "days") --> Get the time range for today between the beginning of today and the beginning of tommorow - 1 second
now - unit.send(timeunit)..now + 1.send(timeunit) - 1.seconds - unit.send(timeunit)
end
将帮助您请求时间范围。所以,当你要求类似的东西时,
time_range(0, "days")
它将返回0天前(今天)的时间范围;
Wed, 07 Sep 2016 00:00:00 UTC +00:00..Wed, 07 Sep 2016 23:59:59 UTC +00:00
然后您可以简单地查询数据库对象并使用;
计算范围内的所有内容Calls.where(transfer_date: time_range(unit, timeunit)).count