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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With