Skip to content

Commit 9bca339

Browse files
committed
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.
1 parent 71dad57 commit 9bca339

2 files changed

Lines changed: 40 additions & 3 deletions

File tree

‎lib/time.rb‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -624,13 +624,48 @@ def httpdate(date)
624624
# You must require 'time' to use this method.
625625
#
626626
def xmlschema(time)
627-
if /\A\s*
627+
pattern = /\A\s*
628628
(-?\d+)-(\d\d)-(\d\d)
629629
T
630630
(\d\d):(\d\d):(\d\d)
631631
(\.\d+)?
632632
(Z|[+-]\d\d(?::?\d\d)?)?
633-
\s*\z/ix =~ time
633+
\s*\z/ix
634+
_xmlschema(pattern, time)
635+
end
636+
alias iso8601 xmlschema
637+
638+
#
639+
# Parses +time+ as a dateTime defined by RFC3339 and converts it to
640+
# a Time object.
641+
#
642+
# ArgumentError is raised if +time+ is not compliant with the format or if
643+
# the Time class cannot represent the specified time.
644+
#
645+
# See #xmlschema for more information on this format.
646+
#
647+
# require 'time'
648+
#
649+
# Time.rfc3339("2011-10-05T22:26:12-04:00")
650+
# #=> 2011-10-05 22:26:12-04:00
651+
#
652+
# You must require 'time' to use this method.
653+
#
654+
def rfc3339(time)
655+
pattern = /\A\s*
656+
(-?\d{4})-(\d\d)-(\d\d)
657+
[T\s]
658+
(\d\d):(\d\d):(\d\d)
659+
(\.\d+)?
660+
(Z|[+-]\d\d(?::?\d\d)?)?
661+
\s*\z/ix
662+
_xmlschema(pattern, time)
663+
end
664+
665+
private
666+
667+
def _xmlschema(pattern, time)
668+
if pattern =~ time
634669
year = $1.to_i
635670
mon = $2.to_i
636671
day = $3.to_i
@@ -656,7 +691,7 @@ def xmlschema(time)
656691
raise ArgumentError.new("invalid xmlschema format: #{time.inspect}")
657692
end
658693
end
659-
alias iso8601 xmlschema
694+
660695
end # class << self
661696

662697
#
@@ -731,4 +766,5 @@ def xmlschema(fraction_digits=0)
731766
end
732767
end
733768
alias iso8601 xmlschema unless method_defined?(:iso8601)
769+
alias rfc3339 xmlschema
734770
end

‎test/test_time.rb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,7 @@ def test_huge_precision
574574
test = $1
575575
define_method(test) {__send__(sub, :xmlschema)}
576576
define_method(test.sub(/xmlschema/, 'iso8601')) {__send__(sub, :iso8601)}
577+
define_method(test.sub(/xmlschema/, 'rfc3339')) {__send__(sub, :rfc3339)}
577578
end
578579

579580
def test_parse_with_various_object

0 commit comments

Comments
 (0)