Help us understand the problem. What is going on with this article?

日付/時間フォーマットのデフォルトを設定

More than 5 years have passed since last update.

Railsで日時を表示する際のデフォルトフォーマットが気に入らなかったので、
デフォルトフォーマットを設定。

まず、Railsのデフォルトはこんな感じ。

> Time.now.to_s
 => 2014-03-03 15:21:57 +0900 

IT関連ではない日本人にとって、 YYYY-MM-DD は慣れていないだろうし、
+0900 は言わずもがななので、 YYYY/MM/DD HH:mm に統一したい。

デフォルトフォーマットの設定は config/initializers/time_formats.rb に。
ファイルがなければ新規作成。
中身はこんな感じに。

config/initializers/time_formats.rb
Time::DATE_FORMATS[:default] = '%Y/%m/%d %H:%M'
Time::DATE_FORMATS[:datetime] = '%Y/%m/%d %H:%M'
Time::DATE_FORMATS[:date] = '%Y/%m/%d'
Time::DATE_FORMATS[:time] = '%H:%M:%S'
Date::DATE_FORMATS[:default] = '%Y/%m/%d'

設定したらWebサーバを再起動。
そうするとこんな感じに表示される。

> Time.now.to_s
 => "2014/03/03 15:22" 

> Time.now.to_s(:date)
 => "2014/03/03" 

> Time.now.to_s(:datetime)
 => "2014/03/03 15:23" 

> Time.now.to_s(:time)
 => "15:23:07" 

ここで使えるフォーマット文字列は strftime の通り。
class Time.strftime

Vit-Symty
スーパー牛さんパワーなどはありません。
https://nautilus-code.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした