学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Ruby on Rails | 日付日時フォーマット

↓↓クリックして頂けると励みになります。


Ruby on Railsで日付日時を日本の形式にフォーマットする方法を紹介します。


まずは、タイムゾーンを日本時間に変更します。
「config/application.rb」ファイルに以下の設定を追加します。

    # タイムゾーンを日本時間に設定
    config.time_zone = 'Asia/Tokyo'



次に「config/application.rb」に以下の設定を追加します。

    # デフォルトのロケールを日本(ja)に設定
    config.i18n.default_locale = :ja



「config/locales」フォルダに「ja.yml」ファイルを新規作成します。


日付以外にも色々書いていますが、必要な部分だけ利用してください。
階層を揃えることが重要です。
新規作成 【config/locales/ja.yml】

ja:
  activerecord:
    attributes:
      user:
        full_name: 氏名
        current_password: パスワード
        password_confirmation: パスワードの確認
        password: パスワード
        email: メールアドレス
        phone_number: 電話番号

  time:
    formats:
        full_date: "%Y年%m月%d日 (%a)"
  views:
    pagination:
      first: "« 最初"
      last: "最後 »"
      previous: "‹ 前"
      next: "次 ›"
      truncate: "..."
  helpers:
    page_entries_info:
      one_page:
        display_entries:
          zero: ""
          one: "<strong>1-1</strong>/1件中"
          other: "<strong>1-%{count}</strong>/%{count}件中"
      more_pages:
        display_entries: "<strong>%{first}-%{last}</strong>/%{total}件中"
  datetime:
    distance_in_words:
      half_a_minute: "30秒前後前"
      less_than_x_seconds:
        one:   "1秒前"
        other: "%{count}秒前"
      x_seconds:
        one:   "1秒"
        other: "%{count}秒前"
      less_than_x_minutes:
        one:   "1分"
        other: "%{count}分前"
      x_minutes:
        one:   "約1分前"
        other: "%{count}分前"
      about_x_hours:
        one:   "約1時間前"
        other: "約%{count}時間前"
      x_days:
        one:   "1日前"
        other: "%{count}日前"
      about_x_months:
        one:   "約1ヶ月前"
        other: "約%{count}ヶ月前"
      x_months:
        one:   "1ヶ月前"
        other: "%{count}ヶ月前"
      almost_x_years:
        one:   "1年弱前"
        other: "%{count}年弱前"
      about_x_years:
        one:   "約1年前"
        other: "約%{count}年前"
      over_x_years:
        one:   "1年以上前"
        other: "%{count}年以上前"        



「l」メソッドを利用し、日付をフォーマットします。

<%= l(report.created_at)  %>



デフォルトで表示されます。

デフォルト日付表示
デフォルト日付表示



設定したフォーマットを利用するには以下のようにします。

<%= l(report.created_at, format: :full_date) %>


フォーマット指定
フォーマット指定



「time_ago_in_words」メソッドを利用すると、「〜日前」のような表記をすることができます。

<%= time_ago_in_words(report.created_at) %>


日付表記
日付表記



↓↓クリックして頂けると励みになります。