提交 17f5d8e0 编写于 作者: A Andrew White

Keep sub-second resolution when wrapping a DateTime value

Add `DateTime#usec` and `DateTime#nsec` so that `ActiveSupport::TimeWithZone`
keeps sub-second resolution when wrapping a `DateTime` value.

Fixes #10855
上级 b3bc3aa5
* Add `DateTime#usec` and `DateTime#nsec` so that `ActiveSupport::TimeWithZone` keeps
sub-second resolution when wrapping a `DateTime` value.
Fixes #10855
*Andrew White*
* Fix `ActiveSupport::Dependencies::Loadable#load_dependency` calling
`#blame_file!` on Exceptions that do not have the Blamable mixin
......
......@@ -80,6 +80,16 @@ def to_i
seconds_since_unix_epoch.to_i
end
# Returns the fraction of a second as microseconds
def usec
(sec_fraction * 1_000_000).to_i
end
# Returns the fraction of a second as nanoseconds
def nsec
(sec_fraction * 1_000_000_000).to_i
end
private
def offset_in_seconds
......
......@@ -292,7 +292,7 @@ def advance(options)
end
end
%w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
%w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
class_eval <<-EOV, __FILE__, __LINE__ + 1
def #{method_name} # def month
time.#{method_name} # time.month
......@@ -300,10 +300,6 @@ def #{method_name} # def month
EOV
end
def usec
time.respond_to?(:usec) ? time.usec : 0
end
def to_a
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
end
......
......@@ -327,6 +327,16 @@ def test_to_i
assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
end
def test_usec
assert_equal 0, DateTime.civil(2000).usec
assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).usec
end
def test_nsec
assert_equal 0, DateTime.civil(2000).nsec
assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).nsec
end
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
......
......@@ -445,6 +445,11 @@ def test_usec_returns_0_when_datetime_is_wrapped
assert_equal 0, twz.usec
end
def test_usec_returns_sec_fraction_when_datetime_is_wrapped
twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
assert_equal 500000, twz.usec
end
def test_utc_to_local_conversion_saves_period_in_instance_variable
assert_nil @twz.instance_variable_get('@period')
@twz.time
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册