显示相对时间

通常用相对时间来表示当前的日期互动性会更强一点,Rails已经内置了对相对时间的支持,time_ago_in_words 这个helper就可以实现,比如要显示发表评论的相对时间用代码:
发表点评于<%= time_ago_in_words(comment.created_at) %> 前
默认的格式是英文的,当需要统一风格显示中文的相对时间只需要简单两步的修改:

time_ago_in_words 实际上是调用的 distance_of_time_in_words 这个函数,并且以 Time.now 作为第二个参数,application_helper.rb中加入以下代码:
def time_ago_in_words(from_time, include_seconds = false)
distance_of_time_in_words(from_time, Time.now, include_seconds)
end

  1. 重写 distance_of_time_in_words 函数,把其中中的英文改成中文就可以了,application_helper.rb中加入以下代码(其中的中文可以换成你喜欢的表达方式):

def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
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)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round

case distance_in_minutes
    when 0..1
        return (distance_in_minutes == 0) ? '不到 1 分钟' : '1 分钟' unless include_seconds
    case distance_in_seconds
        when 0..4   then '不到 5 秒'
        when 5..9   then '不到 10 秒'
        when 10..19 then '不到 20 秒'
        when 20..39 then '半分钟'
        when 40..59 then '不到 1 分钟'
        else             '1 分钟'
    end

    when 2..44           then "#{distance_in_minutes} 分钟"
    when 45..89          then '大约 1 小时'
    when 90..1439        then "大约 #{(distance_in_minutes.to_f / 60.0).round} 小时"
    when 1440..2879      then '1 天'
    when 2880..43199     then "#{(distance_in_minutes / 1440).round} 天"
    when 43200..86399    then '大约 1 个月'
    when 86400..525599   then "#{(distance_in_minutes / 43200).round} 个月"
    when 525600..1051199 then '大约 1 年'
else                      "#{(distance_in_minutes / 525600).round} 年"

end
end

你可能感兴趣的:(显示相对时间)