Domanda

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?

È stato utile?

Soluzione

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).

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top