Reputation: 6341
I'm working on an application (training class app) that currently saves and displays the training class start date time as UTC.
Migration
class CreateTrainingClasses < ActiveRecord::Migration[5.2]
def change
create_table :training_classes do |t|
t.datetime :starts_at
end
end
end
Date Time Select
Date Time Display
However, I want to save and display local time (CST). I've updated the date time select form field to display the desired local time.
<%= form.label :starts_at %>
<p><%= form.datetime_select :starts_at, default: Time.now.in_time_zone("Central Time (US & Canada)"), ampm: true %></p>
And I've updated the display to show local time. However, it is now showing the wrong time—even when I create a new training class.
<td><%= training_class.starts_at.in_time_zone("Central Time (US & Canada)").strftime("%B %d, %Y %I:%M %p") %></td>
How do I save and display the correct local time for both the form and the class display?
Upvotes: 3
Views: 1504
Reputation: 4709
You need to set time_zone in application.rb
config.time_zone = 'Central Time (US & Canada)'
Then restart server
Reference: https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
Upvotes: 4
Reputation: 122
I would say neither. I don't know the Ruby syntax, but why not persist the time zone data with the time itself? This is how it's implemented in SQL Server for comparison:
"The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time."
Upvotes: 0