Handling Timezone implementing ActiveSupport::TimeZone in Ruby on Rails 6.1 and PostgreSQL
I'm sure I'm missing something obvious here, but I'm converting an old project and I've searched everywhere and can't find a clear answer..... Quick question that's been bugging me - I've been struggling with this for a few days now and could really use some help... I'm working with a question with time zone handling in my Rails 6.1 application that uses PostgreSQL. The scenario arises when I store timestamps in UTC but retrieve them in a different time zone. For instance, I have a model `Event` with a `starts_at` timestamp field. When saving a new event, I ensure the time is in UTC, but upon fetching the record, I seem to get the time adjusted to the local time zone of the server, which causes confusion, especially when users from different time zones are involved. Hereโs the code Iโm using to save the event: ```ruby # app/models/event.rb class Event < ApplicationRecord validates :starts_at, presence: true end # In the controller def create @event = Event.new(event_params) @event.starts_at = ActiveSupport::TimeZone['UTC'].local_to_utc(params[:event][:starts_at]) if @event.save redirect_to @event else render :new end end ``` And when I retrieve the events: ```ruby # In the controller def index @events = Event.all end ``` When I render the events in the view, I format the time like this: ```erb <% @events.each do |event| %> <p>Event starts at: <%= event.starts_at.strftime('%Y-%m-%d %H:%M:%S %Z') %></p> <% end %> ``` However, the output shows the time in the serverโs local timezone, leading to confusion about the actual event start time. Iโve tried setting the time zone in the application configuration using `config.time_zone = 'UTC'`, but it doesn't seem to change how the timestamps are displayed. I've also attempted using `in_time_zone` method on `starts_at` when displaying it, but that also doesn't yield the expected results. Should I be storing the timestamps in a different way or is there a better way to handle this scenario using `ActiveSupport::TimeZone`? My PostgreSQL database is set to use UTC, and I want to keep it that way for consistency across different users' time zones. Any guidance on how to properly manage time zones in Rails for this use case would be greatly appreciated! My development environment is Windows. What am I doing wrong? This is happening in both development and production on CentOS. I appreciate any insights! I've been using Ruby for about a year now. The project is a microservice built with Ruby. Cheers for any assistance!