在Rails项目中,我想找到两个日期之间的差异,然后以自然语言显示.就像是
- >> (date1 - date2).to_natural_language
- "3 years,2 months,1 week,6 days"
基本上是this的红宝石.
Google和Rails API没有任何东西.我发现一些事情会让你有一个单位的差异(即两个日期之间有多少个星期),而不是能够准确地计算几个月,几个月,几个星期的日子.
解决方法
其他答案可能不会提供您要查找的输出类型,因为Rails帮助者不是提供几年,几个月的字符串,而是显示最大的单位.如果你正在寻找更细分的东西,这里是另一个选择.将此方法粘贴到帮助器中:
- def time_diff_in_natural_language(from_time,to_time)
- 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_seconds = ((to_time - from_time).abs).round
- components = []
- %w(year month week day).each do |interval|
- # For each interval type,if the amount of time remaining is greater than
- # one unit,calculate how many units fit into the remaining time.
- if distance_in_seconds >= 1.send(interval)
- delta = (distance_in_seconds / 1.send(interval)).floor
- distance_in_seconds -= delta.send(interval)
- components << pluralize(delta,interval)
- end
- end
- components.join(",")
- end
然后在一个视图中,你可以说:
- <%= time_diff_in_natural_language(Time.now,2.5.years.ago) %>
- => 2 years,6 months,2 days
给定的方法只能下降到几天,但如果需要,可以轻松地扩展到更小的单位.