且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何按用户转换日期时间

更新时间:2023-11-01 23:22:46

当我制作一个带有调度事件的应用程序时,我不得不向 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