Forum: Ruby on Rails Forcing times in the database to UTC?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D3eacdff36f1b3ac3165c9f528810853?d=identicon&s=25 gregspurrier (Guest)
on 2007-01-16 01:51
(Received via mailing list)
Howdy All,

I'd like to make sure that every timestamp that is stored in the
database is in UTC.  I set ActiveRecord::Base.default_timezone to :utc
and that takes care of the automatically-managed updated_at and
created_at fields, but the rest are still at the mercy of the code
remembering to make sure that times are converted to UTC before calling
save on the model.

At first glance, it seems that forcing the developer to manually
convert ensure that all times are in UTC before saving is error prone.
Wouldn't it be simpler to force all times to UTC on their way to being
stored in the database if default_timezone == :utc?

I've patched
activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
to have the quote() method covert Time and DateTime objects to UTC
before producting the quoted value for use with the database:

          ....
          when Time, DateTime
            if ActiveRecord::Base.default_timezone == :utc
              # Make sure we've got UTC going into the database
              "'#{quoted_date(value.dup.utc)}'"
            else
              "'#{quoted_date(value)}'"
            end
          ....

The dup is because the utc method is side-effecting and I prefer not to
catch the caller by surprise with a changed value.

This works for me and passes the ActiveRecord unit tests with the MySQL
adaptor.

My question is:  is this a reasonable approach to solving this problem?
 It's a simple change, so I'm wondering why it hasn't been done in the
past...  Some unintended consequence I'm not thinking of?

Any insight would be appreciated.

Thanks,
Greg
This topic is locked and can not be replied to.