LoginSignup
61
54

More than 3 years have passed since last update.

Twitter風の〜分前を実装する(Rails編)

Last updated at Posted at 2014-08-26

ダッシュボードを作っていて最新データの更新時刻を一覧表示にしたけど、パッとみても時間がわかりにくい...ということでTwitter風の〜分前って表示を実装しようと思いました。

Twitter風の〜分前を実装する(JavaScript/Vue編)を書きました(2019/12/1)
https://qiita.com/bellx2/items/379dd0e22256bc1895b0

調査

作ろうと思ったらその名もズバリなエントリーを発見。

time_ago_in_wordsでtwitterライクな「○分前」を表示

というか、すでにRailsのDateHelperにtime_ago_in_wordsというファンクションがあるようです。なるほど。

実装

日本語で表示するために

config/application.rb
config.i18n.default_locale = :ja
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}年以上"

あとは、該当の箇所に

time_ago_in_words(alertDate)+"前"

とすれば表示できます。

タイムゾーンが設定されていない場合

HerokuはUTCで時差は9時間。Rails側のTimeZoneを変更する方法もあると思うのだがうまく反映できるか不明なので、とりあえず9時間マイナスで表示のみ変更で暫定対応。

time_ago_in_words(alertDate-9.hour)

課題

  • タイムゾーンを正しく設定する
  • ja.yamlはどこから探すのが良いのか調べる(参考にしたサイトのが不十分だったため)
61
54
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
61
54