In my rails app, there are certain travel expenses where I want them set and displayed in raw UTC time.
I've added this to my config/application.rb
config.time_zone = 'UTC'
config.active_record.default_timezone = :utc
There seems to be a set (blank datetime_select), a save (stored in db as UTC), a display (<%= obj.date.to_utc %> and a modify (prefilled datetime_select).
I'm not having problems with the set, save or display. I've added a fix for the set - a before_save call to append ' +0000' to the time attribute. But I'm running into problems with modifying a datetime.
When I view the edit page, the datetime_select will display the previously save datetime. However, it displays the hours 6 hours earlier. Instead of 10pm, it will display 4pm.
Here is my form datetime_select:
<%= activity_log_item.object.date.utc %>
<%= activity_log_item.datetime_select :date,
ampm: true,
use_short_month: true,
minute_step: 15, order: [:month, :day, :year, :hour, :minute] %>
</td>
The first line will print out the expected time (10pm), which I've confirmed is the same time in the db. However, the datetime_select form will display 4pm.
I would like all times in my app to be set, saved and displayed in UTC unless I explicitly parse it otherwise - using Time.zone =
or .in_time_zone
for example.
I'm using Rails 3.2.12.
You will need to use
Time.zone.now
orTime.now.in_time_zone
exclusively in your application in order to force Rails to use the timezone you've set in your config file. To default thedate_select
object to the time in UTC, simply initialize the new record withnew_record.date = Time.zone.now
, perhaps in your controller'snew
action.Background
By default, Rails will convert all datetime fields to UTC before storing them in the database. When Rails reads a record back out, it will convert that UTC timestamp to be in the zone specified in your config file.
Time.now
will return a Time object in the timezone that your web server is configured to use.Time.zone.now
will convert the system time to be in the timezone in your config file.Example
Here's a practical example. My computer (aka the server) is configured in EST. I have a Rails app configured to use PST. The database stores everything in UTC