简体   繁体   English

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

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

I'm using Rails 4.2. 我正在使用Rails 4.2。 I have a Date that I'd like to convert to a DateTime . 我有一个Date ,我想转换为DateTime If I use the existing to_datetime method, it converts it in GMT. 如果我使用现有的to_datetime方法,它会在GMT中转换它。 (I've looked at threads for about an hour now and couldn't find this exact problem so apologies in advance if it exists!) (我现在已经看了大约一个小时的线程,并且找不到这个确切的问题,所以如果它存在,请提前道歉!)

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

If I then try to use in_time_zone , it converts it to the current time zone but also subtracts the offset from the date. 如果我然后尝试使用in_time_zone ,它会将其转换为当前时区,但也会从日期中减去偏移量。

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

How can I convert an existing Date to a DateTime in the current time zone? 如何将现有Date转换为当前时区的DateTime时间?

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

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

I had a similar issue, and I did this: 我有类似的问题,我这样做了:

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

Which basically re-creates the date as a Time instance while being in the target timezone, at midnight, without "moving" the Time instance around. 这基本上是在目标时区,午夜时间内重新创建日期作为时间实例,而不会“移动”时间实例。

The accepted answer didn't work for me because Date.current.to_time converted the date to my :local timezone, which is UTC, instead of my configured timezone, which is PST. 接受的答案对我不起作用,因为Date.current.to_time将日期转换为我的:local时区,即UTC,而不是我配置的时区,即PST。

Instead, I used Date.current.in_time_zone.to_datetime , which I found here: https://www.varvet.com/blog/working-with-time-zones-in-ruby-on-rails/ 相反,我使用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