如何基于每个用户转换日期时间

时间:2016-07-14 02:39:07

标签: ruby-on-rails timezone utc

我已经保留了我的application.rb,默认情况下它以UTC格式存储日期时间。

现在处于UI级别(仅用于显示)我想将日期时间转换为用户特定的时区。

如何转换从postgresql获取的UTC日期时间,然后将其转换为我将为每个用户存储的时区。

我想使用Offset进行此转换,如:-5:00 or +4:00

这样做是否可以,因为我只是检查了一些位置,看起来它们在赛季中的偏移发生了变化。

E.g。弗吉尼亚州从UTC -5到UTC -4,具体取决于月份。 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?

1 个答案:

答案 0 :(得分:1)

当我使用计划事件创建应用程序时,我不得不将时区添加到用户模型以抵消其计划。

当我记录偏移量时,我使用了以下代码:

<%= time_zone_select "user", 
                     "timezone", 
                     ActiveSupport::TimeZone.us_zones, 
                     {default: "Mountain Time (US & Canada)"},
                     {class: "form-control"} %>

因为Rails有time zones built into their ActiveSupport model.如果您希望用户是全球用户,可以使用ActiveSupport::TimeZone.all

以下是time_zone_select

的一些信息

然后根据您的使用方式,您可以设置

Time.zone = current_user.timezone unless current_user.nil?

application.rb文件中的类似内容。

更新

我个人用它在控制器中设置了必要的2个动作的时区。

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