5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで2つの日付の差分をそれっぽく表示する(distance_of_time_in_words)

Last updated at Posted at 2016-09-17

したいこと

ビューヘルパーにdistance_of_time_in_wordsというのがありますが、
ちょっとカスタマイズしてつかいたかったので、若干つくりました

やりたかったことは、こんなことです。

できたこと

2つの日時を引数にとり、その差分をこんなフォーマットにする

     "1日前のとき  => 1日",
     "11日前のとき => 11日",
     "21日前のとき => 21日",
     "31日前のとき => 1ヶ月",
     "41日前のとき => 1ヶ月"

コード

  # 日付を比較する
  # @param [Time] from_time 日付
  # @param [Time] to_time   日付
  # @return [String] 1ヶ月未満の時 => oo日, 一ヶ月以上の時 => ooヶ月
  def distance_of_months(from_time, to_time = Time.current)
    from_time = from_time.to_time if from_time.respond_to?(:to_time)
    to_time = to_time.to_time     if to_time.respond_to?(:to_time)
    from_time, to_time = to_time, from_time if from_time > to_time
    distance_in_minutes = ((to_time - from_time)/60.0).round
    I18n.with_options :scope => 'datetime.distance_in_words' do |locale|
      case distance_in_minutes
      when 0...43200 then locale.t :x_days,   :count => (distance_in_minutes.to_f / 1440.0).round
      else                locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
      end
    end
  end
5
4
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?