Ruby on rails created_at format show

时间:2015-08-05 11:15:16

标签: ruby-on-rails ruby

我在time添加了application_helper.rb方法。

我想在视图中显示<%= message.created_at %>存在,如何使用相对类型代替<%= message.created_at %>来显示,例如2分钟前,1周前

def relative_time(start_time)
  diff_seconds = Time.now - start_time

  case diff_seconds
  when 0 .. 59
    puts "#{diff_seconds} seconds ago"
  when 60 .. (3600-1)
    puts "#{diff_seconds/60} minutes ago"
  when 3600 .. (3600*24-1)
    puts "#{diff_seconds/3600} hours ago"
  when (3600*24) .. (3600*24*30) 
    puts "#{diff_seconds/(3600*24)} days ago"
  else
    puts start_time.strftime("%m/%d/%Y")
  end
end

1 个答案:

答案 0 :(得分:1)

已经有一种称为time_ago_in_words的方法(感谢Pavan提到这个别名,我总是使用distance_in_time_in_words_from_now)。要更改句子的显示方式,您需要配置语言环境:

en:
  datetime:
    distance_in_words:
      half_a_minute: half a minute
      less_than_x_seconds:
        one: less than 1 second
        other: less than %{count} seconds
      x_seconds:
        one: 1 second
        other: '%{count} seconds'
      less_than_x_minutes:
        one: less than a minute
        other: less than %{count} minutes
      x_minutes:
        one: 1 minute
        other: '%{count} minutes'
      about_x_hours:
        one: about 1 hour
        other: about %{count} hours
      x_days:
        one: 1 day
        other: '%{count} days'
      about_x_months:
        one: about 1 month
        other: about %{count} months
      x_months:
        one: 1 month
        other: '%{count} months'
      about_x_years:
        one: about 1 year
        other: about %{count} years
      over_x_years:
        one: over 1 year
        other: over %{count} years
      almost_x_years:
        one: almost 1 year
        other: almost %{count} years