保存具有特定时区的 Rails 记录
如何使用自己的特定时区保存柏林的活动以及使用不同时区的蒂华纳的下一个活动?
用户被要求选择事件的城市,作为例如+02:00的来源。
我希望收到这样的时间代码:
eventstart = "2011-07-22T18:00:00+02:00"
您将如何创建该表单?
更新:
实现保存为标准 UTC 是可以的,原因有很多。因此,现在我正在更改视图中的时间字符串,以根据用户的当地时间为 eventstart 呈现 *distance_to_time_in_words*。
蒂华纳的活动,从柏林时间观看:
old_zone = Time.zone
#=> "Berlin"
Time.zone = "Tijuana"
t = Time.zone.parse(eventstart.to_s[0..-7])
#=> 2011-07-22 18:00:00 +08:00
Time.zone = old_zone
#=> "Berlin"
distance_of_time_in_words(Time.now.in_time_zone, t)
#=> "9 hours"
很麻烦,但目前有效。欢迎提出改进意见!
How to save an event in Berlin with its own specific timezone and the next event in Tijuana with a different one?
The user is asked to choose a City for the event, as a source for e.g. +02:00.
I would like to receive a time code like this:
eventstart = "2011-07-22T18:00:00+02:00"
How would you go about creating that form?
UPDATE:
Realized saving as standard UTC is fine for many reasons. So now I am altering a time string in the view to present a *distance_to_time_in_words* for eventstart, depending on the user's local time.
Event in Tijuana, viewing from Berlin time:
old_zone = Time.zone
#=> "Berlin"
Time.zone = "Tijuana"
t = Time.zone.parse(eventstart.to_s[0..-7])
#=> 2011-07-22 18:00:00 +08:00
Time.zone = old_zone
#=> "Berlin"
distance_of_time_in_words(Time.now.in_time_zone, t)
#=> "9 hours"
cumbersome, but works for now. Improvement ideas welcome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在数据库中添加一个
time_zone
列,并在表单中使用time_zone_select
让用户选择要为其创建事件的time_zone
。在模型中,您可以将日期时间转换为区域特定的日期时间并将 utc 存储在数据库中。您可以使用如下所示的助手
Add a
time_zone
column to your database and usetime_zone_select
in your form to let user select thetime_zone
for which he is creating event.And in the model you can convert the datetime to zone specific datetime and store utc in the database. You can use helper something like below