LoginSignup
0
1

More than 3 years have passed since last update.

Railsでcreated_atやupdated_atなどの日時をフォーマットで表示するにする方法

Last updated at Posted at 2021-03-30

はじめに

Viewの部分でテーブルからcreated_atやupdated_atを呼び出し表示させると、以下のようになってしまいます。

index.html.erb
  # 省略
  <td><%= user.id %></td>
  <td><%= user.name %></td>
  <td><%= user.email %></td>
  <td><%= user.age %></td>
  <td><%= user.introduction %></td>

  #updated_at
  <td><%= user.updated_at %></td>

  #created_at
  <td><%= user.created_at %></td>
  #省略

日時がおかしい

日時が書かれている右側に「UTC」という文字が表示されてしまっています。
実は、何も設定しないと、日本時間ではなく、世界標準時間(UTC)が表示されてしまうからです。
今回は世界標準時間から日本時間に変更する方法を紹介します。

時間を日本時間にする

日本時間にするには、config/application.rbを編集する必要があります。このファイルに、
config.time_zone = 'Tokyo
を加えます。

config/application.rb
require_relative "boot"

require "rails/all"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Myapp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.1

    # Configuration for the application, engines, and railties goes here.
    #
    # These settings can be overridden in specific environments using the files
    # in config/environments, which are processed later.
    #
    # config.time_zone = "Central Time (US & Canada)"
    # config.eager_load_paths << Rails.root.join("extras")

    #以下のコードを加える
    config.time_zone = 'Tokyo'
  end
end

すると、以下のようになります。

時間が日本時間になった

日本時間に変更はされました!
が、今度は「+0900」と表示されています。これは、世界標準時間との時差を表しています。
これも表示させてくありません。さらに、「2021-03-23」のような表示より、「2021年03月30日」と表示させた方が、日本人にはみやすいのでフォーマットを使って表示を変更させていきます。

フォーマットを指定して見やすくする

フォーマットを指定するには新たにファイルを作成する必要があります。config/initializetime_formats.rbファイルを作成し、以下のフォーマットを記入します。

config/initialize/time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y年 %m月 %d日 %H時 %M分'

コードを記入したら、最後にviewを以下のように変更します。

index.html.erb
  #省略
  <td><%= user.id %></td>
  <td><%= user.name %></td>
  <td><%= user.email %></td>
  <td><%= user.age %></td>
  <td><%= user.introduction %></td>

  #to_s(:dateTime_jp)を加える
  <td><%= user.updated_at.to_s(:datetime_jp) %></td>
  <td><%= user.created_at.to_s(:datetime_jp) %></td>
  #省略

viewを変更して再起動すると、

フォーマットが適応された!

しっかりフォーマットが適応されています。

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