Skip to content

Commit

Permalink
Fix: timezone bug - rounding problem
Browse files Browse the repository at this point in the history
Why this commit?

   TimeWithZone instances were unexpectedly being rounded up.

What changes were made and why?

   Internally, .to_f was being called on TimeWithZone instances.
This can lead to inaccuracies if Rationals are involved. Using .to_r
instead of .to_f will be more accurate, but it does come with a
slight computational cost.
  • Loading branch information
benkoshy committed Oct 25, 2020
1 parent 7e2d843 commit 0719b94
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def at_with_coercion(*args)
# Time.at can be called with a time or numerical value
time_or_number = args.first

if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
if time_or_number.is_a?(ActiveSupport::TimeWithZone)
at_without_coercion(time_or_number.to_r).getlocal
elsif time_or_number.is_a?(DateTime)
at_without_coercion(time_or_number.to_f).getlocal
else
at_without_coercion(time_or_number)
Expand Down
9 changes: 9 additions & 0 deletions activesupport/test/core_ext/time_with_zone_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,15 @@ def test_use_zone_raises_on_invalid_timezone
assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
end

def test_end_of_period_timezone_equality_with_DateTime
Time.use_zone "UTC" do
without_time_zone = "2019-01-01 00:00:00Z".to_time.end_of_month
zoned = without_time_zone.in_time_zone

assert_equal(Time.zone.at(without_time_zone), Time.zone.at(zoned))
end
end

def test_time_zone_getter_and_setter
Time.zone = ActiveSupport::TimeZone["Alaska"]
assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
Expand Down

0 comments on commit 0719b94

Please sign in to comment.