Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model's datetime field is stored differently on heroku from localhost

Steps:

On my localhost server I select the time Jan 18, 2013 10 am - 11 am in my browser located in the Pacific time zone. I then select the exact same time on my production server on heroku.

As you can see the outputs of what is saved to the database are different. I want production to behave as localhost and take into account the timezone when storing the time as UTC. What is causing this? The heroku server is in EST, but that does not account for this behavior.

Controller:

  def create
    puts params[:event][:starts_at]
    @event = Event.create!(params[:event])
    puts @event.starts_at
  end

Output Localhost:

Fri Jan 18 2013 10:00:00 GMT-0800 (PST)

2013-01-18 18:00:00 UTC

Output Heroku (production):

Fri Jan 18 2013 10:00:00 GMT-0800 (PST)

2013-01-18 10:00:00 UTC

Schema:

 t.datetime "starts_at"

Env:

Ruby on Rails 3.2.11

Ruby 1.9.3

Postgres

like image 547
John Avatar asked Oct 21 '22 20:10

John


1 Answers

Background on how PostgreSQL deals with date/time

I think your issue is covered in this answer from another SO question:

  • Ignoring timezones altogether in Rails and PostgreSQL

Specifically this answer:

  • https://stackoverflow.com/a/9576170/33204

Use this query for time in UTC format:

SELECT * FROM tbl WHERE time_col > (now() AT TIME ZONE 'UTC')::time

Use this query for time in local timezone:

SELECT * FROM tbl WHERE time_col > now()::time

Rails & ActiveRecords & date/time

This rails/rails github issue also discusses it:

  • ActiveRecord converts time to default zone on write; assumes UTC on read

There is a comment by pixeltrix which says the following:

@deathbob sorry for the late reply - the accepted values for config.active_record.default_timezone are either :utc or :local. If you set it to something other than :utc it will assume :local so what you're seeing is the expected behavior.

To fix the time in ActiveRecords so that it is always dealt with as UTC you can set the following variable:

config.active_record.default_timezone = :utc
like image 90
slm Avatar answered Oct 24 '22 09:10

slm