Вопрос

I am having problems with a query because midnight conversion is not working as expected.

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'"

I was expecting the generated sql to be

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

My Time zone is GMT -3. If i change the time zone so it matches GMT -5 the generated sql is

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

Is there any way to ignore the timezone so the query behaves like expected?

Это было полезно?

Решение

Timezones are relative to UTC (0000), so you gotta remove it from your Date.

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

Now, just get rid from the compensated hours.

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

Not sure if there is a cleaner way to do it, but it worked for me (Ruby 1.9.3p385).

Другие советы

Date.current or Date.today.midnight.utc Should have solved the problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top