From 8950f6bf148b9069ddd73a06e406cbe60c59d99a Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 30 Apr 2026 16:33:41 -0700 Subject: [PATCH] Add Time#rfc3339 and Time.rfc3339 This allows easier transition of code using DateTime to using Time. Time#rfc3339 is an alias to #xmlschema and is just for consistency. Time.rfc3339 is similar to Time.xmlschema, but allows a space between the date and time, while Time.xmlschema does not (it requires a "T"). Introduce a Time._xmlschema private method so that Time.xmlschema and Time.rfc3339 can share most of the implementation. --- lib/time.rb | 42 +++++++++++++++++++++++++++++++++++++++--- test/test_time.rb | 1 + 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/lib/time.rb b/lib/time.rb index e6aab3f..f4302fa 100644 --- a/lib/time.rb +++ b/lib/time.rb @@ -624,13 +624,48 @@ def httpdate(date) # You must require 'time' to use this method. # def xmlschema(time) - if /\A\s* + pattern = /\A\s* (-?\d+)-(\d\d)-(\d\d) T (\d\d):(\d\d):(\d\d) (\.\d+)? (Z|[+-]\d\d(?::?\d\d)?)? - \s*\z/ix =~ time + \s*\z/ix + _xmlschema(pattern, time) + end + alias iso8601 xmlschema + + # + # Parses +time+ as a dateTime defined by RFC3339 and converts it to + # a Time object. + # + # ArgumentError is raised if +time+ is not compliant with the format or if + # the Time class cannot represent the specified time. + # + # See #xmlschema for more information on this format. + # + # require 'time' + # + # Time.rfc3339("2011-10-05T22:26:12-04:00") + # #=> 2011-10-05 22:26:12-04:00 + # + # You must require 'time' to use this method. + # + def rfc3339(time) + pattern = /\A\s* + (-?\d{4})-(\d\d)-(\d\d) + [T\s] + (\d\d):(\d\d):(\d\d) + (\.\d+)? + (Z|[+-]\d\d(?::?\d\d)?)? + \s*\z/ix + _xmlschema(pattern, time) + end + + private + + def _xmlschema(pattern, time) + if pattern =~ time year = $1.to_i mon = $2.to_i day = $3.to_i @@ -656,7 +691,7 @@ def xmlschema(time) raise ArgumentError.new("invalid xmlschema format: #{time.inspect}") end end - alias iso8601 xmlschema + end # class << self # @@ -731,4 +766,5 @@ def xmlschema(fraction_digits=0) end end alias iso8601 xmlschema unless method_defined?(:iso8601) + alias rfc3339 xmlschema end diff --git a/test/test_time.rb b/test/test_time.rb index 55964d0..229d73a 100644 --- a/test/test_time.rb +++ b/test/test_time.rb @@ -574,6 +574,7 @@ def test_huge_precision test = $1 define_method(test) {__send__(sub, :xmlschema)} define_method(test.sub(/xmlschema/, 'iso8601')) {__send__(sub, :iso8601)} + define_method(test.sub(/xmlschema/, 'rfc3339')) {__send__(sub, :rfc3339)} end def test_parse_with_various_object