LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】世界一簡単なcreated.at(updated.at)日本語表記

Posted at

はじめに

railsではロンドン?の時刻表示がデフォになっていますが、簡単に日本語表記で表すことができます。

本記事では簡単にやる方法を簡潔に書きます。

開発環境

  • Ruby2.6.6

実際のコード

まずは、application.rbに以下を記述します。

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

次に、config/locateの中にja.ymlのファイルを作り、以下を記述します。

config/locate/ja.yml
ja:
  datetime:
    distance_in_words:

      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}ヶ月"
      about_x_years:
        one:   "約1年"
        other: "約%{count}年"
      over_x_years:
        one:   "1年以上"
        other: "%{count}年以上"

あとは、表示させたいviewに追記部分を加えるだけ!

index.html.erb
<h1>sample</h1>
<h3>Tweet一覧</h3>
<%= link_to "新規投稿へ", tweets_new_path %>
<div class="tweets-container">
  <% @tweets.each do |t| %>
    <div class="tweet">
      <%= t.body %>
         #ここから
      <time datetime="<%= t.created_at %>">
      <%= time_ago_in_words(t.created_at) %>前
      </time>  
     #ここまで
    </div>
  <% end %>
</div>

最後に

世界一簡単にRailsでcreated.atやupdated.atをTwitterのように(〇分前、〇日前)日本語表記する方法についてご紹介しました。

簡単に実装可能なのでぜひ試してみてみてくださいね!

参考記事:https://qiita.com/bellx2/items/30906a7832ef4ff4c886

最後まで読んでいただき、ありがとうございました。

0
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
0
0