views:

1115

answers:

3

My created_at timestamps are stored in UTC:

>> Annotation.last.created_at
=> Sat, 29 Aug 2009 23:30:09 UTC +00:00

How do I convert one of them to 'Eastern Time (US & Canada)' (taking into account daylight savings)? Something like:

Annotation.last.created_at.in_eastern_time
+5  A: 

Use the in_time_zone method of the DateTime class

Loading development environment (Rails 2.3.2)
>> now = DateTime.now.utc
=> Sun, 06 Sep 2009 22:27:45 +0000
>> now.in_time_zone('Eastern Time (US & Canada)')
=> Sun, 06 Sep 2009 18:27:45 EDT -04:00
>> quit

So for your particular example

Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)')
Steve Weet
+2  A: 

Set your timezone to Eastern Time.

You can set your default timezone in config/environment.rb

config.time_zone = "Eastern Time (US & Canada)"

Now all records you pull out will be in that time zone. If you need different time zones, say based on a user timezone you can change it with a before_filter in your controller.

class ApplicationController < ActionController::Base

  before_filter set_timezone

  def set_timezone
    Time.zone = current_user.time_zone
  end
end

Just make sure you are storing all your times in the database as UTC and everything will be sweet.

railsninja
A: 

If you add this to your /config/environment.rb

config.time_zone = 'Eastern Time (US & Canada)'

Then you can cell

Annotation.last.created_at.in_time_zone

to get the time in the specified time zone.

Eifion