Re: Another Dates question

Scott Barron
2005-07-06T15:52:16Z

On Jul 6, 2005, at 11:35 AM, Michael King wrote:

> Is there an easy way to handle timezones?
>
> I am going to have users using my app in EDT, CDT and eventually
> worldwide.
>
> - Michael

Time zones.  Get ready for some real fun!  With the wise guidance of
Jamis Buck I''ve managed to get time zones in my latest app functioning
properly.  I''m also writing a nice set of TZ recipes for our book
(plug), so look for that (if we ever get it finished ;).

At any rate, how far you''ll need to go can depend on what
you''re doing.
  First thing is to have the DB store times in UTC, you can turn that
flag on with ActiveRecord::Base.default_timezone = :utc.  Then you''ll
want to give the user a time zone attribute, see the TimeZone class for
this.  You can either just have the string stored with the user, or you
can set up an AR Aggregate to directly give you the proper TimeZone
object.

(If you go with just a string you''ll need to use
TimeZone[user.timezone] in place of user.timezone in the following
examples, the examples are shown using an aggregate)

If you''re just storing timestamps in the DB, for example the created_at
of a blog post, then you''ve just got to worry about TimeZone#adjust,
and it could work basically like this:

<%= user.timezone.adjust(post.created_at) %>

If the user is inputting a time, let''s say a reminder, then
you''ve got
to TimeZone#unadjust it before it goes into the DB (and gets converted
to UTC) and then TimeZone#adjust it on display, for example

# Reminder model, belongs to User
def before_save
   self.remind_me_on = user.timezone.unadjust(remind_me_on.utc)
end

<%= user.timezone.adjust(reminder.remind_me_on) %>

It''s also nice to set the TZ environment variable to UTC for your rails
application.  Doing this depends how you launch it.

Of course you can spruce this up a bit with some helpers and other
things, but that''s the basic idea of it.  I''ll leave relative
times
(e.g. 5 hours from now) as an exercise for the reader ;)

Note that the TimeZone class currently does not handle DST and that in
reality time zones are not an easy thing to deal with.  Jamis has a far
better understanding of it all than I do and I hope he someday has the
time to implement a great TZ class for Rails (I know he _really_ wants
to ;).

Enjoy
-Scott


_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org