Skip to content

Commit

Permalink
Merge pull request #20600 from mtsmfm/xmlschema-should-display-more-t…
Browse files Browse the repository at this point in the history
…han-6-digits

TimeWithZone#xmlschema should be able to display more than 6 digits
  • Loading branch information
pixeltrix committed Oct 2, 2015
2 parents a9f66de + 602ffe2 commit c80b114
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
9 changes: 4 additions & 5 deletions activesupport/lib/active_support/time_with_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ def self.name
'Time'
end

PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N".freeze }
PRECISIONS[0] = '%FT%T'.freeze

include Comparable
attr_reader :time_zone

Expand Down Expand Up @@ -142,11 +145,7 @@ def inspect
#
# Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00"
def xmlschema(fraction_digits = 0)
fraction = if fraction_digits.to_i > 0
(".%06i" % time.usec)[0, fraction_digits.to_i + 1]
end

"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
"#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z'.freeze)}"
end
alias_method :iso8601, :xmlschema

Expand Down
4 changes: 2 additions & 2 deletions activesupport/test/core_ext/time_with_zone_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,14 @@ def test_xmlschema_with_fractional_seconds
@twz += 0.1234560001 # advance the time by a fraction of a second
assert_equal "1999-12-31T19:00:00.123-05:00", @twz.xmlschema(3)
assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(6)
assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(12)
assert_equal "1999-12-31T19:00:00.123456000100-05:00", @twz.xmlschema(12)
end

def test_xmlschema_with_fractional_seconds_lower_than_hundred_thousand
@twz += 0.001234 # advance the time by a fraction
assert_equal "1999-12-31T19:00:00.001-05:00", @twz.xmlschema(3)
assert_equal "1999-12-31T19:00:00.001234-05:00", @twz.xmlschema(6)
assert_equal "1999-12-31T19:00:00.001234-05:00", @twz.xmlschema(12)
assert_equal "1999-12-31T19:00:00.001234000000-05:00", @twz.xmlschema(12)
end

def test_xmlschema_with_nil_fractional_seconds
Expand Down

0 comments on commit c80b114

Please sign in to comment.