BigC BigC - 7 months ago 20
Ruby Question

Rails: print UTC time by default

I have a non-ActiveRecord server which is sending data to another service. That server expects to receive instructions including UTC in the format:

"%Y-%m-%d %H:%M:%S.%L"
. I already have an time_format.rb initializer that overrides
Time::DATE_FORMATS[:default]
Is there a way I can configure my server so that
Time.now.to_s
will by default print UTC time, without me having to specify
Time.now.utc
every time I call it? I'm using ruby 2.0.0 and Rails 4.

I tried adding
config.time_zone = 'London'
to
config/application.rb
but that did not work.

Answer

I don't think ActiveRecord should have anything to do with it, but maybe I'm misunderstanding. Like Sergio said, set your applications timezone to UTC.

Here's my Rails app. My computer is in PST. My Rails app is set to UTC.

 > Time.now
 => 2014-01-22 21:52:38 -0800
 > Time.zone.name
 => "UTC"
 > Time.zone.now
 => Thu, 23 Jan 2014 05:52:43 UTC +00:00
 > Time.now.utc
 => 2014-01-23 05:52:45 UTC

I would strongly advise not overriding Time.now. That can only lead to the dark side.

Comments