Rails是具有日期和时间的表查询

时间:2013-07-15 16:05:20

标签: ruby-on-rails date rails-activerecord arel

我遇到查询问题,因为午夜转换无法正常工作。

time = Date.today.midnight #=> Mon, 15 Jul 2013 00:00:00 BRT -03:00

time.class #=> ActiveSupport::TimeWithZone

condition = Task.arel_table[:scheduled_to].gt(time)

condition.to_sql #=> "`tasks`.`scheduled_to` > '2013-07-15 03:00:00'"

我期待生成的sql是

`tasks`.`scheduled_to` > '2013-07-15 00:00:00'"

我的时区是GMT -3。如果我更改时区使其与GMT -5匹配,则生成的sql为

condition.to_sql #=> "`tasks`.`scheduled_to` > '2013-07-15 05:00:00'"
  • Rails 4.0.0
  • Ruby 2.0.0p247

有没有办法忽略时区,所以查询的行为与预期的一样?

2 个答案:

答案 0 :(得分:1)

时区是相对于UTC(0000),所以你必须从你的日期中删除它。

DateTime.now.midnight.utc #=> '2013-08-23 03:00:00 +0000'

现在,摆脱补偿的时间。

DateTime.now.midnight.utc.change({:hour => 0, :min => 0}) #=> '2013-08-23 00:00:00 +0000'

不确定是否有更简洁的方法,但它对我有用(Ruby 1.9.3p385)。

答案 1 :(得分:0)

Date.currentDate.today.midnight.utc应该已经解决了问题。