distance_of_time_in_words_to_now不准确

时间:2015-01-06 19:31:24

标签: ruby-on-rails

所以,也许我做错了,但在rails 3.2.19中,我得到了这个结果:

irb(main):009:0> include ActionView::Helpers::DateHelper
=> Object
irb(main):009:0> distance_of_time_in_words_to_now(DateTime.now + 1.day)
=> "1 day"
irb(main):010:0> distance_of_time_in_words_to_now(DateTime.now + 1.month)
=> "about 1 month"
irb(main):011:0> distance_of_time_in_words_to_now(DateTime.now + 2.month)
=> "about 1 month"
irb(main):012:0> distance_of_time_in_words_to_now(DateTime.now + 3.month)
=> "3 months"

为什么添加2个月会显示about 1 month

或者,任何人都可以建议更准确的自然语言日期宝石或方法吗?

解决方案:

我想我的旧版's rails是问题所在。所以,我使用了chronic_duration gem并最终获得了这个小片段:

opt = { weeks: true, units: 2, joiner: ' and ' }.merge!(options)
ChronicDuration.output((date_time.to_datetime - DateTime.now).to_i * 24 * 60 * 60, opt)

产生

"2 mos and 3 days"

1 个答案:

答案 0 :(得分:1)

这对我来说很好。

[11] pry(main)> include ActionView::Helpers::DateHelper
=> Object

[12] pry(main)> distance_of_time_in_words_to_now(DateTime.now + 1.day)
=> "1 day"

[13] pry(main)> distance_of_time_in_words_to_now(DateTime.now + 1.month)
=> "about 1 month"

[14] pry(main)> distance_of_time_in_words_to_now(DateTime.now + 2.month)
=> "about 2 months"

[15] pry(main)> distance_of_time_in_words_to_now(DateTime.now + 3.month)
=> "3 months"

您使用的是哪种版本的导轨?也许这是一个已修复的错误。我正在运行4.2 beta。