Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 962
Waynn Lue Avatar asked Aug 20 '15 00:08

Waynn Lue


1 Answers

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

Time.zone.at(Date.current.to_time).to_datetime
like image 128
Waynn Lue Avatar answered Oct 19 '22 19:10

Waynn Lue