Schneems
Schneems

Reputation: 15828

ActiveRecord DateTime field not matching object

i've got a Course model, which has a datetime attribute. If I look at it from the database i get one time, and if i look at it from the object i get a different date & time.

>> Course.last.attribute_for_inspect :datetime
=> "\"2012-01-04 01:00:00\""
>> Course.last.datetime
=> Tue, 03 Jan 2012 19:00:00 CST -06:00

Does anyone know why this value is different, and what I can do to fix it? The time from Course.last.datetime is correct, but my queries on the course table aren't working correctly due to the mix-up.

Upvotes: 0

Views: 1350

Answers (2)

Marcelo Austria
Marcelo Austria

Reputation: 951

Configuring your Rails App Timezone in application.rb

set config.active_record.default_timezone to :local as it is set to :utc by default in the application.rb

paste this code in your application.rb

config.active_record.default_timezone = :local #or :utc
config.time_zone = "Singapore" #your timezone

Upvotes: 0

mu is too short
mu is too short

Reputation: 434685

From the fine manual:

attribute_for_inspect(attr_name)
Returns an #inspect-like string for the value of the attribute attr_name.
[...]
Date and Time attributes are returned in the :db format.

So, when attribute_for_inspect is used for a datetime, it will return the string that the database uses for that value. Rails stores times in the database in UTC and any sensible database will use ISO 8601 for formatting timestamps on the way in and out.

2012-01-04 01:00:00 is the UTC timestamp in ISO 8601 format. When Rails returns a datetime, it converts it to an ActiveSupport::TimeWithZone instance and includes a timezone adjustment based on the timezone that you have configured in your application.rb. You're using the CST timezone and that's six hours behind UTC; subtracting six hours from 01:00 gives you 19:00 and you lose a day from crossing midnight. The human friendly format, Tue, 03 Jan 2012 19:00:00 CST -06:00, is just how ActiveSupport::TimeWithZone represents itself when inspected and the console uses x.inspect to display x.

As far as fixing your queries goes, just use t.utc before sending in a time t and you should be good.

Upvotes: 2

Related Questions