繁体   English   中英

在Rails 4中,将当前时区中的Date转换为DateTime的最佳方法是什么?

[英]What's the best way to convert a Date to a DateTime in the current timezone in Rails 4?

我正在使用Rails 4.2。 我有一个Date ,我想转换为DateTime 如果我使用现有的to_datetime方法,它会在GMT中转换它。 (我现在已经看了大约一个小时的线程,并且找不到这个确切的问题,所以如果它存在,请提前道歉!)

irb(main):030:0> Date.current
=> Wed, 19 Aug 2015
irb(main):031:0> Date.current.to_datetime
=> Wed, 19 Aug 2015 00:00:00 +0000

如果我然后尝试使用in_time_zone ,它会将其转换为当前时区,但也会从日期中减去偏移量。

irb(main):032:0> Date.current.to_datetime.in_time_zone
=> Tue, 18 Aug 2015 17:00:00 PDT -07:00

如何将现有Date转换为当前时区的DateTime时间?

这是我能想到的最佳答案。

Time.zone.at(Date.current.to_time).to_datetime

我有类似的问题,我这样做了:

Time.use_zone("Europe/Berlin") do
  midnight = Time.zone.parse(@date.to_s)
end

这基本上是在目标时区,午夜时间内重新创建日期作为时间实例,而不会“移动”时间实例。

接受的答案对我不起作用,因为Date.current.to_time将日期转换为我的:local时区,即UTC,而不是我配置的时区,即PST。

相反,我使用Date.current.in_time_zone.to_datetime ,我在这里找到: httpsDate.current.in_time_zone.to_datetime

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM