Rails: Time, DateTime, Timezones…. wait, what?

Everything happens in UTC!
Thats the one basic thing you must know about handling Times in Rails.

SomeModel.create(:time_attribute => Time.now)
SomeModel.create(:time_attribute => Time.zone.now)

Both lines will insert the same value into the database –> UTC+0. ActiveRecord will automaticly convert the given time. Therefore the config.time_zone in application.rb only controlls the default timezone and not the Timezone format the database will store the attribute.

You can also safely compare times that are in different zones – you don’t need to convert them to some common timezone.

A good link I found while adding time zones to our own project was this: http://www.redguava.com.au/2010/12/rails-basics-handling-user-timezones-in-rails/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>