3

是否有 Rails 助手或其他 Ruby 方法来获取 DateTime 对象并转换为类似的东西?

  • “13 天”(如果不到一个月)
  • “3 个月”(如果不到一年)
  • “1年3个月”

我熟悉 Rails内置的 helpers,但正在寻找能给我上面输出的东西。

4

2 回答 2

2

也许distance_of_time_in_words是您正在寻找的:

distance_of_time_in_words(from_time, from_time + 50.minutes)        # => about 1 hour
distance_of_time_in_words(from_time, 50.minutes.from_now)           # => about 1 hour
distance_of_time_in_words(from_time, from_time + 15.seconds)        # => less than a minute
distance_of_time_in_words(from_time, from_time + 15.seconds, true)  # => less than 20 seconds
distance_of_time_in_words(from_time, 3.years.from_now)              # => about 3 years
distance_of_time_in_words(from_time, from_time + 60.hours)          # => 3 days
distance_of_time_in_words(from_time, from_time + 45.seconds, true)  # => less than a minute
distance_of_time_in_words(from_time, from_time - 45.seconds, true)  # => less than a minute
distance_of_time_in_words(from_time, 76.seconds.from_now)           # => 1 minute
distance_of_time_in_words(from_time, from_time + 1.year + 3.days)   # => about 1 year
distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
于 2013-04-30T22:23:37.053 回答
2

Rails 辅助方法是您想要的,然后您使用 i18n 对其进行自定义。查看这些答案:Rails distance_of_time_in_words 返回“en,about_x_hours”

另外,看看这是如何实现的: https ://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/date_helper.rb

于 2013-04-30T22:43:20.830 回答