格式化相对日期

时间:2010-04-20 03:03:22

标签: ruby datetime rubygems nlp

是否有红宝石宝石会格式化相对于当前时间的日期?我希望输出像“明天下午5点”,“下周四下午5:15”,我不太关心确切的输出,只要它是自然语言的相对日期

2 个答案:

答案 0 :(得分:7)

如果你有轨道,我认为 ActionView::Helpers::DateHelper#distance_of_time_in_words 可以帮助你。

require 'rubygems'
require 'action_view'
include ActionView::Helpers::DateHelper

from_time = Time.now
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)              # => over 3 years
distance_of_time_in_words(from_time, from_time + 60.hours)          # => about 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 + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years

to_time = Time.now + 6.years + 19.days
distance_of_time_in_words(from_time, to_time, true)     # => over 6 years
distance_of_time_in_words(to_time, from_time, true)     # => over 6 years
distance_of_time_in_words(Time.now, Time.now)           # => less than a minute

如果相对于当前时间,请使用distance_of_time_in_words_to_now代替distance_of_time_in_words

如果您的应用是基于磁道的,只需在视图中使用distance_of_time_in_wordsdistance_of_time_in_words_to_nowtime_ago_in_words

答案 1 :(得分:-3)

尝试宝石'慢性'

它完全符合您的要求。