如何按用户转换日期时间 [英] How to convert datetime on a per user basis
问题描述
我保留了我的 application.rb 原样,默认情况下它以 UTC 格式存储日期时间.
I have left my application.rb as it was and by default it is storing datetime in UTC.
现在在 UI 级别(仅用于显示)我想将日期时间转换为用户特定的时区.
Now at the UI level (for displaying only) I want to convert the datetime to the user specific timezone.
如何转换从 postgresql 获得的 UTC 日期时间,然后将其转换为我将为每个用户存储的时区.
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.
我想使用偏移量进行此转换,例如:-5:00 或 +4:00
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.
例如弗吉尼亚州根据月份从 UTC -5 到 UTC -4.http://www.timeanddate.com/time/zone/usa/richmond
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?
推荐答案
当我制作一个带有调度事件的应用程序时,我不得不向 User 模型添加时区以抵消它们的调度.
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"} %>
因为 Rails 在其 ActiveSupport 模型中内置了时区.您可以使用ActiveSupport::TimeZone.all
如果您希望用户成为全球用户.
Because Rails has time zones built into their ActiveSupport model. You could use ActiveSupport::TimeZone.all
if you wanted users to be global.
以下是有关 time_zone_select
然后根据你的使用方式,你可以设置
Then depending on how you use it, you can just set
Time.zone = current_user.timezone unless current_user.nil?
或您的 application.rb
文件中的类似内容.
or something similar in your application.rb
file.
更新
我个人使用它来设置控制器中仅有的 2 个必要操作的时区.
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
这篇关于如何按用户转换日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!