更正 rails DateTime.parse 中夏令时的时间 [英] Correcting time for daylight savings in rails DateTime.parse

查看:39
本文介绍了更正 rails DateTime.parse 中夏令时的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是增加了关于时区和 DST 问题的数百万个问题.

Just adding to the million questions about time zone and DST issues out there.

我有一个包含单独的日期和时间字段的表单,我将它们组合起来创建一个像这样的 DateTime

I have a form with separate date and time fields that I combine to create a DateTime like so

start_time = DateTime.parse("#{parse_date(form_date)} #{form_start_time} #{Time.zone}")

如果我在 2012 年 8 月 21 日和 15:00 填写表单,那么这些就是我在重新加载表单时看到的值.如果我查看模型中的 start_time 属性,它会正确设置为 Tue, 21 August 2012 15:00:00 EST +10:00.

If I fill out my form with 21 Aug 2012 and 15:00, then these are the values that I see when I reload my form. If I then look at my start_time attribute in my model it is correctly set to Tue, 21 Aug 2012 15:00:00 EST +10:00.

如果我在今年晚些时候使用夏令时开始使用日期(我在澳大利亚),就会出现我遇到的问题.如果我使用 21 Dec 2012 和 15:00 然后检查 start_time 我看到 Fri, 21 Dec 21 16:00:00 EST +11:00.

The problem I am having occurs if I use a date later this year once daylight savings kicks in (I am in Australia). If I use 21 Dec 2012 and 15:00 then check start_time I see Fri, 21 Dec 2012 16:00:00 EST +11:00.

我对这个问题的解释是日期保存在我当前的时区 (+10:00) 中,因为这是我告诉 DateTime.parse 要做的.但是,当返回该值时,Rails 会查看日期并说嘿,这是 12 月的夏令时"并返回 +11:00 时区的时间.

My interpretation of the problem is that the date is being saved in my current time zone (+10:00) as this is what I have told DateTime.parse to do. However when the value is returned, Rails is looking at the date and saying 'hey, it's daylight savings time in December' and returning the time in the +11:00 time zone.

我想要做的是告诉 DateTime.parse 如果 DST 生效,将时间保存在 +11:00 时区.显然将 Time.zone 传递到我的字符串中并不能实现这一点.有没有一种简单的方法可以做到这一点?我可以看到使用 Time#dst 的方法吗?但我怀疑这会创建一些非常难看的复杂代码.我想可能有一种我缺少的内置方式.

What I want to do is tell DateTime.parse to save the time in the +11:00 time zone if DST is in effect. Clearly passing Time.zone into my string doesn't achieve this. Is there a simple way of doing this? I can see ways of doing it using Time#dst? but I suspect that this is going to create some really ugly convoluted code. I thought there might be a built in way that I'm missing.

推荐答案

这是我目前的解决方案.我希望有人有更好的.

Here's my solution so far. I'm hoping someone has a better one.

start_time = DateTime.parse "#{date} #{(form_start_time || start_time)} #{Time.zone}"
start_time = start_time - 1.hour if start_time.dst? && !Time.now.dst?
start_time = start_time + 1.hour if Time.now.dst? && start_time.dst?

它似乎有效,但我还没有对其进行严格测试.我怀疑它可以被美化和缩短,但我认为这是可读和可以理解的.有什么改进吗?

It seems to work but I haven't rigorously tested it. I suspect it could be prettied up and shortened but I think this is readable and understandable. Any improvements?

这篇关于更正 rails DateTime.parse 中夏令时的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆