Lance Pollard
Lance Pollard

Reputation: 79218

Save Datetime in UTC, view/query in User's timezone in Rails?

What is the standard for saving times in one zone and viewing them in another? I have this in my environment.rb:

config.time_zone = 'UTC'

But I want to render it, and do queries like "all posts created today" in their timezone, where beginning_of_day returns the beginning of the day in their timezone rather than UTC. Is rails already handling the conversion in the background?

Here's the issue:

@now = Time.now
 => Wed Jan 26 09:50:04 -0600 2011 
User.count(:conditions => ["created_at > ?", @now])
  SQL (1.3ms)   SELECT count(*) AS count_all FROM `users` WHERE (created_at > '2011-01-26 09:50:04') 
 => 1 
@now = Time.now.utc
 => Wed Jan 26 15:50:10 UTC 2011 
User.count(:conditions => ["created_at > ?", @now])
  SQL (1.2ms)   SELECT count(*) AS count_all FROM `users` WHERE (created_at > '2011-01-26 15:50:10') 
 => 0 

Upvotes: 1

Views: 2227

Answers (1)

zetetic
zetetic

Reputation: 47548

ActiveSupport has built-in methods to display time values in any time zone. Typically you'd add a time_zone column to your User model and set it to the user's preferred zone.

@user.update_attribute(:time_zone,'Eastern Time (US & Canada)')

Then when displaying a time value, set the zone to the user's zone.

Time.zone = @user.time_zone
Time.zone.now # shows current time according to @user.time_zone

One approach is to set this in ApplicationController so it is done for each request:

class ApplicationController < ActionController::Base
  before_filter :set_time_zone

  def set_time_zone
    Time.zone = current_user.time_zone if current_user
  end
end

Note: see the API under ActiveSupport::TimeWithZone

Upvotes: 6

Related Questions