23

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?

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76

3 Answers3

22

Here's the best answer I could come up with.

Time.zone.at(Date.current.to_time).to_datetime
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
  • 1
    but local timezone may not be the same as rails timezone as set in `application.rb` with config, so i think `Time.zone.at` may still be a better choice in rails environment – zuo Jan 04 '17 at 09:40
  • 1
    Oh, that's a really good point -- I think that's why I ended up not using it, because it worked for me in local, but not in prod. – Waynn Lue Jan 05 '17 at 00:10
  • This doesn't return the beginning of the day in the current time zone. It is offset based on the local time zone. See Kelly Corrigan's answer. – ryanb Nov 03 '21 at 18:08
8

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.

Martin T.
  • 3,132
  • 1
  • 30
  • 31
  • This one worked for me, but I didn't have to use the `Time.use_zone` block because the app already have the right timezone configured. It was basically `beginning_of_day = Time.zone.parse(@date.to_s)` – Thiago Borges Nov 21 '17 at 13:11
6

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/