Modifying the timezone in Ruby or with ActiveSupport

Sometimes you may need to query an SQL record in ruby and convert the UTC time into a local timezone. This is usually done in a framework like Ruby on Rails. Many web frameworks use the Active Support gem. From their enhanced tooling, they may set the timezone on the thread by calling:
Time.zone = "Requests Time Zone".
The Time class in ruby (w/ ActiveSupport) can then access this by calling the getter method:
Time.zone
Here are some examples of how this plays out in action.
require 'Time'
utc_time_str = '2020-01-02T18:16:35+0000'
# Outputs UTC time.
Time.parse(utc_time_str)
=> 2020-01-02 18:16:35 +0000
# Outputs system timezone. Also can use to_time
Time.parse(utc_time_str).to_localtime
=> 2020-01-02 13:16:35 -0500
# With ActiveSupport you can set the current threads time zone.
# This is how RoR handles setting time zones on web requests.
require 'active_support/all'
# Start with a UTC time (say from an SQL query.
# NOTE: No time zone info in string.
utc_time_str = '2020-1-2 18:16:35'
# Parse time from SQL query declaring as UTC TZ.
utc_time = Time.find_zone('UTC').parse(utc_time_str)
=> Thu, 02 Jan 2020 18:16:35 UTC +00:00
# Set the timezone to convert to. This is done in the request in RoR.
Time.zone = 'Central Time (US & Canada)'
Time.zone.parse(utc_time.to_s)
=> Thu, 02 Jan 2020 12:16:35 CST -06:00
See the TimeZone documentation if you need more info. Hope this may be helpful and please comment if you have any questions or additional advice!

Comments

Popular posts from this blog

Atmosphere Websockets & Comet with Spring MVC

Microservices Tech Stack with Spring and Vert.X