我正在使用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
的时区?
======
UPD
我试图在没有simple_form
的情况下渲染时间。如果我使用
= select_datetime @event.start_time.in_time_zone('Moscow')
它有效。
但为.in_time_zone('Moscow')
设置simple_form
并不能解决问题=(或者,我可能做错了。
我也猜测这可能与simple_form
呈现日期时间的方式有关。如果我使用标准助手,它会为每个字段设置start_time[hours]
(等)之类的值。另一方面,simple_form
设置start_time(4i)
(等等)的值。也许问题就在那里。
答案 0 :(得分:0)
将您的配置设置为:local
并声明您的时区,这将节省您的时区时间(现在不需要方法)。
将此添加到config / application.rb
confit.time_zone = "Moscow"
config.active_record.default_timezone = :local
莫斯科将为您提供所需的+3偏移量,但您可以从this list选择您的位置或靠近它的位置。
确保清除旧记录以确定,然后创建一个新记录,并应在当地时间设置。
以下是本地标志的relevant part of the docs。
答案 1 :(得分:0)
答案 2 :(得分:0)
如果在config / application.rb中正确设置
config.time_zone = "Moscow"
config.active_record.default_timezone = :local
它应该工作。
我使用您首先提供的片段尝试了您的代码,输入显示我测试的任何time_zones的本地时间(如“莫斯科”,“墨尔本”或“America / 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