Rails 5:未正确转换 DateTime 对象时区 [英] Rails 5: Not converting DateTime object timezone correctly

查看:39
本文介绍了Rails 5:未正确转换 DateTime 对象时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题困扰了我一段时间.

This issue has been eating away at me for a while.

我取一个日期时间字符串:

I take a date time string:

[14] pry(#<EventsController>)> params[:event][:ended_at]
=> "05/31/2017 2:00 PM"

我将其转换为 DateTime 对象:

I convert it to a DateTime object:

pry(#<EventsController>)> to_datetime = DateTime.strptime(params[:event][:ended_at], "%m/%d/%Y %H:%M %p")
=> Wed, 31 May 2017 14:00:00 +0000

如果我在 to_datetime 对象上运行 in_time_zone 方法,它会输出太平洋时区的错误时间:

If I run the in_time_zone method on the to_datetime object it outputs the wrong time for pacific timezone:

[16] pry(#<EventsController>)> to_datetime.in_time_zone("Pacific Time (US & Canada)")
=> Wed, 31 May 2017 07:00:00 PDT -07:00

2:00PM"应该和输入的一样.

It should read "2:00PM" the same as how it is entered.

如果我去谷歌检查14:00:00 +0000"是否是 PDT 时间的正确条目,它验证为正确:

If I go to google and check to see if "14:00:00 +0000" is the correct entry for PDT time it verifies as correct:

http://imgur.com/a/ZJ80F

任何关于为什么它不能正确转换的线索?

Any clues about why it's not converting correctly?

推荐答案

错误是 ended_at 被系统配置假定,在这种情况下是 '+0000' 你需要包括ended_at 的原始时区.

the error comes that the ended_at is been assumed by the system configuration that in this case is '+0000' you need to include the original timezone the ended_at is.

irb(main):001:0> date = "05/31/2017 2:00 PM"
=> "05/31/2017 2:00 PM"
irb(main):002:0> to_datetime = DateTime.strptime(date, "%m/%d/%Y %H:%M %p")
=> Wed, 31 May 2017 14:00:00 +0000

请注意,由于系统假定为时区,因此已将其设置为 UTC

Note that this one has already set as UTC since was assumed by the system the timezone

irb(main):001:0> date = "05/31/2017 2:00 PM -0700"
=> "05/31/2017 2:00 PM -0700"
irb(main):002:0> to_datetime = DateTime.strptime(date, "%m/%d/%Y %H:%M %p %z")
=> Wed, 31 May 2017 14:00:00 -0700
irb(main):003:0> new_to_datetime = to_datetime.utc
=> Wed, 31 May 2017 21:00:00 +0000
irb(main):004:0> new_to_datetime.in_time_zone("Pacific Time (US & Canada)")
=> Wed, 31 May 2017 14:00:00 PDT -07:00

更新

@antonio 的评论提到他休息了 1 小时

@antonio's comment mention he was 1 hour off

irb(main):046:0> time = DateTime.strptime(date + " Pacific Time (US & Canada)", "%m/%d/%Y %H:%M %p %Z").class
=> DateTime
irb(main):047:0> time = DateTime.strptime(date + " Pacific Time (US & Canada)", "%m/%d/%Y %H:%M %p %Z")
=> Wed, 31 May 2017 14:00:00 -0800
irb(main):048:0> time.utc.class
=> Time

正如你所看到的,这些是不同的类,这是问题的标志,你可以做的是使用 Time 而不是 DateTime

As you can see these are different classes and that's sign of problems what you can do is use Time instead of DateTime

irb(main):049:0> time = Time.strptime(date + " Pacific Time (US & Canada)", "%m/%d/%Y %H:%M %p %Z")
=> 2017-05-31 14:00:00 -0700
irb(main):050:0> time.class
=> Time

这篇关于Rails 5:未正确转换 DateTime 对象时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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