Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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
(cherry picked from commit 17f5d8e)

Conflicts:
	activesupport/CHANGELOG.md
  • Loading branch information...
commit 5b790ca7b8b52868ae2a37546f205db38ac14a46 1 parent ad01b8d
@pixeltrix pixeltrix authored
View
6 activesupport/CHANGELOG.md
@@ -1,5 +1,11 @@
## unreleased ##
+* Add `DateTime#usec` and `DateTime#nsec` so that `ActiveSupport::TimeWithZone` keeps
+ sub-second resolution when wrapping a `DateTime` value.
+ Fixes #10855
+
+ *Andrew White*
+
* Make `Time.at_with_coercion` retain the second fraction and return local time.
Fixes #11350
View
10 activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -79,6 +79,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
View
6 activesupport/lib/active_support/time_with_zone.rb
@@ -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
View
10 activesupport/test/core_ext/date_time_ext_test.rb
@@ -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
View
5 activesupport/test/core_ext/time_with_zone_test.rb
@@ -450,6 +450,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
Please sign in to comment.
Something went wrong with that request. Please try again.