ruby - 格式化相对日期

标签 ruby datetime rubygems nlp

是否有 ruby​​ gem 可以根据当前时间格式化日期?我想要像“明天下午 5 点”、“下星期四下午 5 点 15 分”这样的输出,我不太关心确切的输出,只要它是自然语言中的相对日期即可

最佳答案

如果你有rails,我想 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

如果您的应用是基于 Rails 的,只需在 View 中使用 distance_of_time_in_wordsdistance_of_time_in_words_to_nowtime_ago_in_words

关于ruby - 格式化相对日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672267/

相关文章:

ruby-on-rails - Cron 作业和后台任务

css - 使用 Compass 函数而不使用 Compass 来编译样式表

python - 在 Python 中为昨天构建正确的 MySQL 日期时间格式的字符串

sql - 从sql中给定的日期时间中提取时间和星期几

python - 如何在不添加参数的情况下对基于时间的函数进行单元测试

ruby-on-rails - 尽管 bundle 安装,但未找到 Ruby Gems

ruby-on-rails - 我还需要源 :gemcutter in Gemfile?

javascript - 如何拖放表格?

ruby - Sinatra 如何允许其语法?

ruby - 检测 IDLE 处理器 ruby​​ 的数量