Reputation: 266970
I have left my application.rb as it was and by default it is storing datetime in UTC.
Now at the UI level (for displaying only) I want to convert the datetime to the user specific timezone.
How can I convert the UTC datetime I get from postgresql and then convert it to the timezone that I will store for each user.
I want to make this conversion using the Offset so like: -5:00 or +4:00
Is it ok to do this, because I was just checking some locations and it seems their offset changes during the season.
E.g. virginia goes from UTC -5 to UTC -4 depending on the month. http://www.timeanddate.com/time/zone/usa/richmond
If UTC is not consistant then I should just store the zone in the database for each user?
Upvotes: 0
Views: 65
Reputation: 1173
When I made an app with scheduling events, I had to add timezones to the User model to offset their scheduling.
When I recorded the offset, I used the following code:
<%= time_zone_select "user",
"timezone",
ActiveSupport::TimeZone.us_zones,
{default: "Mountain Time (US & Canada)"},
{class: "form-control"} %>
Because Rails has time zones built into their ActiveSupport model. You could use ActiveSupport::TimeZone.all
if you wanted users to be global.
Here's some info on time_zone_select
Then depending on how you use it, you can just set
Time.zone = current_user.timezone unless current_user.nil?
or something similar in your application.rb
file.
UPDATE
I personally used it to set the timezone in the controller on the only 2 actions where it was necessary.
def index
@user = current_user
@pending = @user.share_events.where("time > ?", DateTime.now.in_time_zone(@user.timezone))
@complete = @user.share_events.where("time <= ?", DateTime.now.in_time_zone(@user.timezone))
end
def new
@user = current_user
Time.zone = @user.timezone
@post = Post.find(params[:post_id])
@share_event = ShareEvent.new
end
Upvotes: 1