I'm using Rails 4.2. I have a Date
that I'd like to convert to a DateTime
. If I use the existing to_datetime
method, it converts it in 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.
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?
这是我能想到的最佳答案。
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.
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.