Jonah Jonah - 5 months ago 27
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
). Eg,

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

Output: A
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

I know that I can set the timezone to the desired one, create the
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.


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

Time.use_zone('America/Chicago') {'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')