LoginSignup
0
0

【Ruby on rails】日時を日本時間で表示する

Last updated at Posted at 2023-11-05

はじめに

プログラミングを勉強して2か月半ほどです。
プログラミングスクールを卒業し、現在就職活動をしています。

今回はオリジナルアプリの中で、日時を日本時間で表示してみたので共有したいと思います。

@jnchito(Junichi Ito)さんの投稿を参考にさせて頂きました。
 とても分かりやすく参考になりました。
 ありがとうございます。

Let's start!!!

時間を表示する

時間を表示するときは、表示したいモデルのcreated_atカラムを取得します。

index.html.erb
<%= destination.created_at %>

しかし、これでは以下のように少し見づらい表示になります。
271ECEB5-ED00-45CF-BDBA-562AF0CF3B23_4_5005_c.jpeg

この世界基準表記を変えていきましょう。

タイムゾーンを日本時間に変更する

config/application.rbに以下の設定をします。

config/application.rb
module HermitPurple
  class Application < Rails::Application
    #中略
    config.time_zone = 'Tokyo'

  end
end

上記の記述で日本時間に変更します。

日本のフォーマットに変更

config/application.rbに以下の設定をします。

config/application.rb
module HermitPurple
  class Application < Rails::Application
    #中略
    config.i18n.default_locale = :ja

  end
end

次に、config/locales/ja.ymlというファイルを作成します。
このファイルに以下のような設定を記述します。

config/locales/ja.yml
ja:
  time:
    formats:
      default: "%Y/%m/%d %H:%M:%S"

lメソッドの記述

最後にviewファイルの記述を変更します。

index.html.erb
<%= l destination.created_at %>

railsにはlメソッドというものがあります。
lメソッドは、config/locales/ja.ymlファイルの表示形式を呼び出します。

この記述後にサーバーを再起動すると表示形式が以下のように変更されます。
DA23D713-A3D4-4B54-8784-6862BEBFCF5D_4_5005_c.jpeg

終わりに

今回は日本時間表示について共有させて頂きました。
みなさんのお役に立てていれば幸いです。

最後まで読んでいただきありがとうございました!

0
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
0
0