Jonah Jonah - 16 days ago 5
Ruby Question

Create a Time object from a timezone and date and time?

I'm embarrassed (and shocked) I can't find a good answer this on SO or google, and please feel free to point me to a dup if there is one, but...

I want a function (in pure ruby ideally but active_support solutions are ok) that works like this:

Input: A datetime string of some reasonable format (eg,

2016-12-25 12:00
) and a timezone. Not an offset, but a timezone, such as
America/Chicago
or
America/New_York
). Eg,

make_time_in_zone('2016-12-25 12:00', 'America/Chicago')


Output: A
Time
or
DateTime
object representing that exact point in time. That is, the function should use the timezone to account for both offsets and daylight savings time adjustments, so that you can know, eg, what the UTC time was when it struck noon on Christmas in
America/Chicago
.

I know that I can set the timezone to the desired one, create the
Time
object, and then the set the timezone back to the system one, but I consider this an unacceptable solution, and want a function that actually supports this use case.

Answer

Rails stores current zone in current Thread, so most correct way is setting a zone for parsing. Something like

Time.use_zone('America/Chicago') { Time.zone.parse('2016-12-25 12:00')}

There is also more "hackish" way, but it is not from public API.

ActiveSupport::TimeZone['America/Chicago'].parse('2016-12-25 12:00')