LoginSignup
4
1

More than 3 years have passed since last update.

「〜分前、〜時間前」の表示方法

Posted at

前提

コントローラーのアクションにより、viewが表示されるようになっていること。
viewが表示されるための適切なインスタンス変数がコントローラー内に定義されていること。

(例 post)

できること

〜分前、〜時間前の時刻の経過示すことができる。

image.png

バージョン

rubyのバージョン ruby-2.6.5
Railsのバージョン Rails:6.0.0

実装の全体像

①日本語化の指示を出す
②datetime、distance_in_words を設定
③viewにtime_ago_in_words(@post.created_at)を記述

実装手順

①日本語化の指示を出す

config/application.rb
config.i18n.default_locale = :ja

②datetime、distance_in_words を設定

config/locales/ja.yml
ja:
  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}年以上"

③viewにtime_ago_in_words(@post.created_at)を記述
以下のどちらかを記述。

<%= time_ago_in_words(@post.created_at) %>前

or

<%= "#{time_ago_in_words(@post.created_at)}前" %>

以上です。

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