在 Rails 中,用英文显示两个日期之间的时间 [英] In Rails, display time between two dates in English

查看:18
本文介绍了在 Rails 中,用英文显示两个日期之间的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 项目中,我想找到两个日期之间的差异,然后以自然语言显示.类似的东西

In a Rails project I want to find the difference between two dates and then display it in natural language. Something like

>> (date1 - date2).to_natural_language 
"3 years, 2 months, 1 week, 6 days"

基本上这个用于红宝石.

Google 和 Rails API 没有发现任何东西.我发现有些东西可以给你一个单位的差异(即,两个日期之间有多少周),但不能准确计算年、月、周、天.

Google and the Rails API haven't turned up anything. I've found some things that will give you the difference in one unit (ie, how many weeks between two dates) but not something that will accurately calculate years, months, weeks, days all together.

推荐答案

其他答案可能没有给出您正在寻找的输出类型,因为 Rails 没有给出一串年份、月份等信息助手只显示最大的单位.如果您正在寻找更细分的东西,这里有另一种选择.将此方法粘贴到 helper 中:

The other answers may not give the type of output that you're looking for, because instead of giving a string of years, months, etc., the Rails helpers just show the largest unit. If you're looking for something more broken down, here's another option. Stick this method into a helper:

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)
      # if above line give pain. try below one  
      # components <<  interval.pluralize(delta)  
    end
  end

  components.join(", ")
end

然后在视图中你可以这样说:

And then in a view you can say something like:

<%= time_diff_in_natural_language(Time.now, 2.5.years.ago) %>
=> 2 years, 6 months, 2 days 

给定的方法只能缩短到几天,但如果需要,可以轻松扩展以添加更小的单位.

The given method only goes down to days, but can be easily extended to add in smaller units if desired.

这篇关于在 Rails 中,用英文显示两个日期之间的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆