0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】日付・時刻の表示を整える `l` メソッドの基本的な使い方

0
Posted at

はじめに

Railsで日付や時刻を表示するとき、これまで strftime を使って毎回フォーマットを書いていました。

<%= @post.created_at.strftime("%Y/%m/%d %H:%M") %>

ところが、l メソッドあることを知った。何気に知らなかったので備忘録がてらメモ

使い方

1. デフォルトのロケールを日本語にする

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

2. ロケールファイルにフォーマットを定義する

config/locales/ja.yml を作成し、日付・時刻のフォーマットを書きます。

config/locales/ja.yml
ja:
  date:
    formats:
      default: "%Y/%m/%d"
      short: "%m/%d"
      long: "%Y年%m月%d日"
  time:
    formats:
      default: "%Y/%m/%d %H:%M"
      short: "%m/%d %H:%M"
      long: "%Y年%m月%d日 %H時%M分"

3. ビューで l を使う

<%= l @post.created_at %>
<%# => 2026/09/25 14:30 %>

format オプションを渡すと、定義した別のフォーマットを使えます。

<%= l @post.created_at, format: :short %>
<%# => 09/25 14:30 %>

<%= l @post.created_at, format: :long %>
<%# => 2026年09月25日 14時30分 %>

strftime と比べて使うメリット

  • フォーマットを ロケールファイルに一元管理 できる
  • 表示形式を変えたいときに、ビューを1つずつ直さなくてよい

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?