Skip to content
Browse files

Make distance_of_time_in_words work with DateTime offsets

Because DateTime#to_time returns self when it has a non-zero offset
and subtracting two DateTime instances returns a Rational then the
distance_of_time_in_words methods outputs an incorrect value.

This is fixed in master because we can rely on Ruby 1.9.3's
implementation of to_time but it can't be fixed on Ruby 1.8.7 as
there is no way to map the DateTime to a Time with a non-zero offset.

We can workaround the problem by casting to Float before doing
the subtraction in the distance_of_time_in_words method.

Closes #8390
  • Loading branch information...
1 parent 18e1227 commit fbf23ed9338f935736dd840ea973fd6372b6ab7d @pixeltrix pixeltrix committed Dec 4, 2012
Showing with 13 additions and 2 deletions.
  1. +3 −2 actionpack/lib/action_view/helpers/date_helper.rb
  2. +10 −0 actionpack/test/template/date_helper_test.rb
View
5 actionpack/lib/action_view/helpers/date_helper.rb
@@ -71,8 +71,9 @@ def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, o
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
- distance_in_minutes = (((to_time - from_time).abs)/60.0).round
- distance_in_seconds = ((to_time - from_time).abs).round
+ distance = (to_time.to_f - from_time.to_f).abs
+ distance_in_minutes = (distance / 60.0).round
+ distance_in_seconds = distance.round
I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
case distance_in_minutes
View
10 actionpack/test/template/date_helper_test.rb
@@ -151,6 +151,16 @@ def test_distance_in_words_with_times
assert_equal "1 minute", distance_of_time_in_words(60.seconds, 0, true)
end
+ def test_distance_in_words_with_offset_datetimes
+ start_date = DateTime.new 1975, 1, 31, 0, 0, 0, '+6'
+ end_date = DateTime.new 1977, 1, 31, 0, 0, 0, '+6'
+ assert_equal("about 2 years", distance_of_time_in_words(start_date, end_date))
+
+ start_date = DateTime.new 1982, 12, 3, 0, 0, 0, '+6'
+ end_date = DateTime.new 2010, 11, 30, 0, 0, 0, '+6'
+ assert_equal("almost 28 years", distance_of_time_in_words(start_date, end_date))
+ end
+
def test_time_ago_in_words
assert_equal "about 1 year", time_ago_in_words(1.year.ago - 1.day)
end

0 comments on commit fbf23ed

Please sign in to comment.
Something went wrong with that request. Please try again.