LoginSignup
1
0

More than 3 years have passed since last update.

【Rails】時刻のJST(日本標準時)への変更

Posted at

Railsアプリは、デフォルトでUTC(協定世界時)タイムゾーンを使用します。日時を扱う際、自動的にActiveSupport::TimeWithZoneクラスを用います。

タイムゾーンの変更

アプリケーションの起動時に任意のタイムゾーンの値にするには、Time.zoneの値の制御が必要です。
製作中のアプリは日本での使用を想定しているため、日本時間に変更します。config/application.rbにconfig.time_zoneから始まる1行を追加します。

config/application.rb
module TweetApp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2
    config.time_zone = 'Asia/Tokyo'
    ...
  end
end

5E583349-31E1-4EE2-929D-6BC0D0788E98.png

これで、日時がJST(日本標準時)で表示されるようになりました!

ですが、このままだと読みづらいので表示を変更します。時刻のフォーマットファイルを作成し…

config/initializers/time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y/%m/%d %H:%M'

あとは以下のコードを投稿時間と更新時間の箇所へと書き換えればOK!

.created_at.to_s(:datetime_jp)
.updated_at.to_s(:datetime_jp)

参考

現場で使える Ruby on Rails 5速習実践ガイド
【Rails】created_at、updated_atを日本時間に変更して良い感じに表示する方法

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0