是否有一个Rails助手或其他Ruby方法来获取DateTime对象并转换成类似的东西?
我熟悉Rails built-in helpers,但正在寻找能够提供上述输出的内容。
答案 0 :(得分:1)
或许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
答案 1 :(得分:1)
Rails helper方法是你想要的,然后你使用i18n自定义它。 看看这些答案:Rails distance_of_time_in_words returns "en, about_x_hours"
另外,看看它是如何实现的: https://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/date_helper.rb