Deepanshu Goyal
Deepanshu Goyal

Reputation: 2813

Rails Handling User specific timezone

I want to display date times created by other users in the time zone the current user is logged in.

I have come across

config.time_zone = 'Central Time (US & Canada)' and
config.active_record.default_timezone = :local

But how can I set this to the timezone of user logged in currently, and will it save the date time saved by other users in their timezone and view to other users in their specific timezone?

Upvotes: 6

Views: 7205

Answers (5)

Artur INTECH
Artur INTECH

Reputation: 7266

class ApplicationController < ActionController::Base
  around_filter :set_time_zone

  def set_time_zone
    if logged_in?
      Time.use_zone(current_user.time_zone) { yield }
    else
      yield
    end
  end
end

https://api.rubyonrails.org/v4.2.5.2/classes/Time.html#method-c-zone-3D

Upvotes: 6

Alex Antonov
Alex Antonov

Reputation: 15146

Consider this code in your ApplicationController.

around_action :switch_time_zone, :if => :current_user

def switch_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

It wraps the current request with Time.use_zone( current_user.time_zone ), which sets the app's current time zone to be the current user's time zone for the entire request and should cause all of your times to be rendered out in the current user's time zone, unless specifically converted to a time zone.

Upvotes: 12

Jun Aid
Jun Aid

Reputation: 504

Use this Gem https://github.com/basecamp/local_time

<%= local_time(@time.created_at) %>

you just have to pass the object like this and it will render the local time of the user logged in. No need to get the local time zone of the current user. It makes time rendering very peaceful :P

Upvotes: 3

ddgd
ddgd

Reputation: 1717

First you'll need to determine user's timezone on the client side and pass it to the controller. You can set it in a coockie:

jQuery(function() {
  var tz = jstz.determine();
  $.cookie('timezone', tz.name(), { path: '/' });
});

In then in your application controller:

class ApplicationController < ActionController::Base
  around_filter :set_user_time_zone

  private

  def set_user_time_zone
    timezone = Time.find_zone(cookies[:timezone])
    Time.use_zone(timezone) { yield }
  end
end

Upvotes: 1

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

We have a asian-europe interacting website. We save everything in UTC time

then we just give the time for the users timezone.

=comment.created_at.in_time_zone

Upvotes: 1

Related Questions