Ruby on Rails being an amazing framework, helps us manage the timezone of our rails application. It gives us access to a lot of helpers, to make our life easier. For example, if you want to change all the date and time of your application to the logged in users time zone, we just have to place the following code in the application_controller.
# app/controllers/application_controller.rb around_action :set_time_zone, if: :current_user private def set_time_zone(&block) Time.use_zone(current_user.time_zone) endWe assume that you have stored the user’s time_zone in your database in the time_zone column. The application to show timezone can be set in your
application.rb, if we don’t set a particular timezone then the application will just show the systems timezone.
config.time_zone = 'Central Time (US & Canada)'If you want to know all the timezone options available in rails, run the
rake -D timecommand in your terminal. Even though rails would take care of the timezone, when we are using certain ruby commands, it gives us our systems timezone and not the one set by rails. So to avoid surprises, we should be aware of the timezones we are exposed to. A rails app, would always be exposed to three timezones:
- System timezone
- Database timezone
- Rails applications own timezone
USE – these give you access to the rails application time (which we can change with respect to the user)
* Time.now * Date.today * Date.today.to_time * Time.parse("2015-07-04 17:05:37") * Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
* Time.current * 2.hours.ago * Time.zone.today * Date.current * 1.day.from_now * Time.zone.parse("2015-07-04 17:05:37") * Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone