我正在使用simple_form
来设置事件的开始和结束时间。但是,它显示错误时区的时间。
我的控制器:
class EventsController < ApplicationController
def new
@event = Event.new(start_time: 1.hour.since(now), end_time: 2.hours.since(now))
render 'edit'
end
...
private
...
def now
Time.zone.now
end
end
我的观点(使用苗条(:
= simple_form_for @event do |f|
= f.input :name
= f.input :start_time
= f.input :end_time
= f.input :camera_ids, collection: Camera.all, as: :check_boxes
= f.button :submit, class:'btn-primary'
我住在+03:00
区。视图分别呈现 2 小时前和 1 小时前。这只是UTC
的时间,但是,我希望它在实际时区。它保存在具有相同时区的数据库中。
我的控制台输出Time.zone.now
或Time.current
是正确的,并且使用+03:00
时区。如何解释simple_form
的时区?
========
更新
我试图在没有simple_form
的情况下渲染时间.如果我使用= select_datetime @event.start_time.in_time_zone('Moscow')
它有效。
但是为simple_form
设置.in_time_zone('Moscow')
并不能解决问题 =( 或者,可能是我做错了。
我也有一个猜测,这可能是关于simple_form
呈现日期时间的方式。如果我使用标准助手,它会为每个字段设置start_time[hours]
(等(等值。 另一方面,simple_form
从start_time(4i)
(依此类推(设置值。也许问题出在那里的某个地方。
要获取运行代码的计算机的当前时区,请执行以下操作:
Time.now.localtime
要更改所有控制器操作EventsController
的时区,您可以查看此答案。
将您的配置设置为:local
并声明您的时区,这将节省您的时区时间(现在不需要方法(。
将此添加到 config/application.rb
confit.time_zone = "Moscow"
config.active_record.default_timezone = :local
莫斯科将为您提供所需的+3偏移量,但您可以从此列表中选择您的位置或靠近它的位置。
确保清除旧记录以确保,然后创建一个新记录,它应该在当地时间设置。
以下是本地标志文档的相关部分。
如果您在 config/application.rb 中设置正确
config.time_zone = "Moscow"
config.active_record.default_timezone = :local
它应该有效。
我首先使用您提供的片段尝试了您的代码,输入显示我测试的任何time_zones的当地时间(例如"莫斯科"、"墨尔本"或"美国/Los_Angeles"(
我不认为问题来自simple_form,因为您直接从控制器(从@event
(注入输入数据。
也许尝试使用一些puts
调试您的控制器以查看返回的时区...:
class EventsController < ApplicationController
def new
start_time = 1.hour.since(now)
end_time = 2.hours.since(now)
puts start_time #<== ...here
puts end_time #<== and here
@event = Event.new(start_time: start_time, end_time: end_time)
render 'edit'
end
def now
Time.zone.now
end
end