Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
Deepanshu Goyal Avatar asked Sep 08 '15 06:09

Deepanshu Goyal


3 Answers

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.

like image 166
asiniy Avatar answered Nov 15 '22 05:11

asiniy


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

like image 6
Artur Beljajev Avatar answered Nov 15 '22 05:11

Artur Beljajev


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

like image 2
Muhammad Junaid Avatar answered Nov 15 '22 05:11

Muhammad Junaid