Ryan Payne
Ryan Payne

Reputation: 6341

How do I display Central Standard Time (CST) in my Rails view?

UTC Time Display

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

Local Time Display (Failed)

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>

enter image description here

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>

enter image description here

Question

How do I save and display the correct local time for both the form and the class display?

References

Upvotes: 3

Views: 1504

Answers (2)

demir
demir

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

Patrick Taylor
Patrick Taylor

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."

https://learn.microsoft.com/en-us/dotnet/standard/datetime/choosing-between-datetime#the-datetimeoffset-structure

Upvotes: 0

Related Questions