Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Rails datetime_select with time zone
like image 590
Ryan Payne Avatar asked Nov 30 '25 07:11

Ryan Payne


1 Answers

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

like image 139
demir Avatar answered Dec 02 '25 20:12

demir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!