1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

created_atとupdated_atの表示を変更する方法

Posted at

created_atとupdated_atを日本時間へ変更する方法

config/application.rbに以下のコードを記述する

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 App
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
    config.time_zone = 'Tokyo'  # ここにタイムゾーンを追記する
  end
end

% rails sでサーバーを再起動すると表記が下記のような日本時間に変わる
Image from Gyazo

表示を変更する

config/initializersディレクトリにtime_formats.rbファイルを作成する
time_formats.rbに下記の記述をする

config/initializers/time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y/%m/%d %H:%M'
                                    # '%Y年 %m月 %d日 %H時 %M分' など表示させたいフォーマットにする

`% rails sでサーバーを再起動

viewへの反映

html.erb
<%= xxx.created_at.to_s(:datetime_jp) %>
<%= xxx.updated_at.to_s(:datetime_jp) %>

created_at, updated_atで
to_sメソッドを呼び出して、引数にフォーマット名を指定
(to_sとは配列を文字列に変換するメソッドで、配列の各要素を文字列に変換して連結した文字列を返す)

下記のように表示が変わる
Image from Gyazo

/参考にした記事/
https://qiita.com/tomo_k09/items/e4f19947d35890500492

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?