[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / lib / time.rb
blobb565130b50c90aca801ff158d7f7134c7f8f1f99
1 # frozen_string_literal: true
2 # shareable_constant_value: literal
4 require 'date'
6 # :stopdoc:
8 # = time.rb
10 # When 'time' is required, Time is extended with additional methods for parsing
11 # and converting Times.
13 # == Features
15 # This library extends the Time class with the following conversions between
16 # date strings and Time objects:
18 # * date-time defined by {RFC 2822}[http://www.ietf.org/rfc/rfc2822.txt]
19 # * HTTP-date defined by {RFC 2616}[http://www.ietf.org/rfc/rfc2616.txt]
20 # * dateTime defined by XML Schema Part 2: Datatypes ({ISO
21 #   8601}[http://www.iso.org/iso/date_and_time_format])
22 # * various formats handled by Date._parse
23 # * custom formats handled by Date._strptime
25 # :startdoc:
27 class Time
29   VERSION = "0.3.0"
31   class << Time
33     #
34     # A hash of timezones mapped to hour differences from UTC. The
35     # set of time zones corresponds to the ones specified by RFC 2822
36     # and ISO 8601.
37     #
38     ZoneOffset = { # :nodoc:
39       'UTC' => 0,
40       # ISO 8601
41       'Z' => 0,
42       # RFC 822
43       'UT' => 0, 'GMT' => 0,
44       'EST' => -5, 'EDT' => -4,
45       'CST' => -6, 'CDT' => -5,
46       'MST' => -7, 'MDT' => -6,
47       'PST' => -8, 'PDT' => -7,
48       # Following definition of military zones is original one.
49       # See RFC 1123 and RFC 2822 for the error in RFC 822.
50       'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4,  'E' => +5,  'F' => +6,
51       'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
52       'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4,  'R' => -5,  'S' => -6,
53       'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
54     }
56     #
57     # Return the number of seconds the specified time zone differs
58     # from UTC.
59     #
60     # Numeric time zones that include minutes, such as
61     # <code>-10:00</code> or <code>+1330</code> will work, as will
62     # simpler hour-only time zones like <code>-10</code> or
63     # <code>+13</code>.
64     #
65     # Textual time zones listed in ZoneOffset are also supported.
66     #
67     # If the time zone does not match any of the above, +zone_offset+
68     # will check if the local time zone (both with and without
69     # potential Daylight Saving \Time changes being in effect) matches
70     # +zone+. Specifying a value for +year+ will change the year used
71     # to find the local time zone.
72     #
73     # If +zone_offset+ is unable to determine the offset, nil will be
74     # returned.
75     #
76     #     require 'time'
77     #
78     #     Time.zone_offset("EST") #=> -18000
79     #
80     # You must require 'time' to use this method.
81     #
82     def zone_offset(zone, year=self.now.year)
83       off = nil
84       zone = zone.upcase
85       if /\A([+-])(\d\d)(:?)(\d\d)(?:\3(\d\d))?\z/ =~ zone
86         off = ($1 == '-' ? -1 : 1) * (($2.to_i * 60 + $4.to_i) * 60 + $5.to_i)
87       elsif zone.match?(/\A[+-]\d\d\z/)
88         off = zone.to_i * 3600
89       elsif ZoneOffset.include?(zone)
90         off = ZoneOffset[zone] * 3600
91       elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
92         off = t.utc_offset
93       elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
94         off = t.utc_offset
95       end
96       off
97     end
99     # :stopdoc:
100     def zone_utc?(zone)
101       # * +0000
102       #   In RFC 2822, +0000 indicate a time zone at Universal Time.
103       #   Europe/Lisbon is "a time zone at Universal Time" in Winter.
104       #   Atlantic/Reykjavik is "a time zone at Universal Time".
105       #   Africa/Dakar is "a time zone at Universal Time".
106       #   So +0000 is a local time such as Europe/London, etc.
107       # * GMT
108       #   GMT is used as a time zone abbreviation in Europe/London,
109       #   Africa/Dakar, etc.
110       #   So it is a local time.
111       #
112       # * -0000, -00:00
113       #   In RFC 2822, -0000 the date-time contains no information about the
114       #   local time zone.
115       #   In RFC 3339, -00:00 is used for the time in UTC is known,
116       #   but the offset to local time is unknown.
117       #   They are not appropriate for specific time zone such as
118       #   Europe/London because time zone neutral,
119       #   So -00:00 and -0000 are treated as UTC.
120       zone.match?(/\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i)
121     end
122     private :zone_utc?
124     def force_zone!(t, zone, offset=nil)
125       if zone_utc?(zone)
126         t.utc
127       elsif offset ||= zone_offset(zone)
128         # Prefer the local timezone over the fixed offset timezone because
129         # the former is a real timezone and latter is an artificial timezone.
130         t.localtime
131         if t.utc_offset != offset
132           # Use the fixed offset timezone only if the local timezone cannot
133           # represent the given offset.
134           t.localtime(offset)
135         end
136       else
137         t.localtime
138       end
139     end
140     private :force_zone!
142     LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # :nodoc:
143     CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # :nodoc:
144     def month_days(y, m)
145       if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
146         LeapYearMonthDays[m-1]
147       else
148         CommonYearMonthDays[m-1]
149       end
150     end
151     private :month_days
153     def apply_offset(year, mon, day, hour, min, sec, off)
154       if off < 0
155         off = -off
156         off, o = off.divmod(60)
157         if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
158         off, o = off.divmod(60)
159         if o != 0 then min += o; o, min = min.divmod(60); off += o end
160         off, o = off.divmod(24)
161         if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
162         if off != 0
163           day += off
164           days = month_days(year, mon)
165           if days and days < day
166             mon += 1
167             if 12 < mon
168               mon = 1
169               year += 1
170             end
171             day = 1
172           end
173         end
174       elsif 0 < off
175         off, o = off.divmod(60)
176         if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
177         off, o = off.divmod(60)
178         if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
179         off, o = off.divmod(24)
180         if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
181         if off != 0 then
182           day -= off
183           if day < 1
184             mon -= 1
185             if mon < 1
186               year -= 1
187               mon = 12
188             end
189             day = month_days(year, mon)
190           end
191         end
192       end
193       return year, mon, day, hour, min, sec
194     end
195     private :apply_offset
197     def make_time(date, year, yday, mon, day, hour, min, sec, sec_fraction, zone, now)
198       if !year && !yday && !mon && !day && !hour && !min && !sec && !sec_fraction
199         raise ArgumentError, "no time information in #{date.inspect}"
200       end
202       off = nil
203       if year || now
204         off_year = year || now.year
205         off = zone_offset(zone, off_year) if zone
206       end
208       if yday
209         unless (1..366) === yday
210           raise ArgumentError, "yday #{yday} out of range"
211         end
212         mon, day = (yday-1).divmod(31)
213         mon += 1
214         day += 1
215         t = make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
216         diff = yday - t.yday
217         return t if diff.zero?
218         day += diff
219         if day > 28 and day > (mday = month_days(off_year, mon))
220           if (mon += 1) > 12
221             raise ArgumentError, "yday #{yday} out of range"
222           end
223           day -= mday
224         end
225         return make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
226       end
228       if now and now.respond_to?(:getlocal)
229         if off
230           now = now.getlocal(off) if now.utc_offset != off
231         else
232           now = now.getlocal
233         end
234       end
236       usec = nil
237       usec = sec_fraction * 1000000 if sec_fraction
239       if now
240         begin
241           break if year; year = now.year
242           break if mon; mon = now.mon
243           break if day; day = now.day
244           break if hour; hour = now.hour
245           break if min; min = now.min
246           break if sec; sec = now.sec
247           break if sec_fraction; usec = now.tv_usec
248         end until true
249       end
251       year ||= 1970
252       mon ||= 1
253       day ||= 1
254       hour ||= 0
255       min ||= 0
256       sec ||= 0
257       usec ||= 0
259       if year != off_year
260         off = nil
261         off = zone_offset(zone, year) if zone
262       end
264       if off
265         year, mon, day, hour, min, sec =
266           apply_offset(year, mon, day, hour, min, sec, off)
267         t = self.utc(year, mon, day, hour, min, sec, usec)
268         force_zone!(t, zone, off)
269         t
270       else
271         self.local(year, mon, day, hour, min, sec, usec)
272       end
273     end
274     private :make_time
275     # :startdoc:
277     #
278     # Takes a string representation of a Time and attempts to parse it
279     # using a heuristic.
280     #
281     # This method **does not** function as a validator.  If the input
282     # string does not match valid formats strictly, you may get a
283     # cryptic result.  Should consider to use `Time.strptime` instead
284     # of this method as possible.
285     #
286     #     require 'time'
287     #
288     #     Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
289     #
290     # Any missing pieces of the date are inferred based on the current date.
291     #
292     #     require 'time'
293     #
294     #     # assuming the current date is "2011-10-31"
295     #     Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500
296     #
297     # We can change the date used to infer our missing elements by passing a second
298     # object that responds to #mon, #day and #year, such as Date, Time or DateTime.
299     # We can also use our own object.
300     #
301     #     require 'time'
302     #
303     #     class MyDate
304     #       attr_reader :mon, :day, :year
305     #
306     #       def initialize(mon, day, year)
307     #         @mon, @day, @year = mon, day, year
308     #       end
309     #     end
310     #
311     #     d  = Date.parse("2010-10-28")
312     #     t  = Time.parse("2010-10-29")
313     #     dt = DateTime.parse("2010-10-30")
314     #     md = MyDate.new(10,31,2010)
315     #
316     #     Time.parse("12:00", d)  #=> 2010-10-28 12:00:00 -0500
317     #     Time.parse("12:00", t)  #=> 2010-10-29 12:00:00 -0500
318     #     Time.parse("12:00", dt) #=> 2010-10-30 12:00:00 -0500
319     #     Time.parse("12:00", md) #=> 2010-10-31 12:00:00 -0500
320     #
321     # If a block is given, the year described in +date+ is converted
322     # by the block.  This is specifically designed for handling two
323     # digit years. For example, if you wanted to treat all two digit
324     # years prior to 70 as the year 2000+ you could write this:
325     #
326     #     require 'time'
327     #
328     #     Time.parse("01-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
329     #     #=> 2001-10-31 00:00:00 -0500
330     #     Time.parse("70-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
331     #     #=> 1970-10-31 00:00:00 -0500
332     #
333     # If the upper components of the given time are broken or missing, they are
334     # supplied with those of +now+.  For the lower components, the minimum
335     # values (1 or 0) are assumed if broken or missing.  For example:
336     #
337     #     require 'time'
338     #
339     #     # Suppose it is "Thu Nov 29 14:33:20 2001" now and
340     #     # your time zone is EST which is GMT-5.
341     #     now = Time.parse("Thu Nov 29 14:33:20 2001")
342     #     Time.parse("16:30", now)     #=> 2001-11-29 16:30:00 -0500
343     #     Time.parse("7/23", now)      #=> 2001-07-23 00:00:00 -0500
344     #     Time.parse("Aug 31", now)    #=> 2001-08-31 00:00:00 -0500
345     #     Time.parse("Aug 2000", now)  #=> 2000-08-01 00:00:00 -0500
346     #
347     # Since there are numerous conflicts among locally defined time zone
348     # abbreviations all over the world, this method is not intended to
349     # understand all of them.  For example, the abbreviation "CST" is
350     # used variously as:
351     #
352     #     -06:00 in America/Chicago,
353     #     -05:00 in America/Havana,
354     #     +08:00 in Asia/Harbin,
355     #     +09:30 in Australia/Darwin,
356     #     +10:30 in Australia/Adelaide,
357     #     etc.
358     #
359     # Based on this fact, this method only understands the time zone
360     # abbreviations described in RFC 822 and the system time zone, in the
361     # order named. (i.e. a definition in RFC 822 overrides the system
362     # time zone definition.)  The system time zone is taken from
363     # <tt>Time.local(year, 1, 1).zone</tt> and
364     # <tt>Time.local(year, 7, 1).zone</tt>.
365     # If the extracted time zone abbreviation does not match any of them,
366     # it is ignored and the given time is regarded as a local time.
367     #
368     # ArgumentError is raised if Date._parse cannot extract information from
369     # +date+ or if the Time class cannot represent specified date.
370     #
371     # This method can be used as a fail-safe for other parsing methods as:
372     #
373     #   Time.rfc2822(date) rescue Time.parse(date)
374     #   Time.httpdate(date) rescue Time.parse(date)
375     #   Time.xmlschema(date) rescue Time.parse(date)
376     #
377     # A failure of Time.parse should be checked, though.
378     #
379     # You must require 'time' to use this method.
380     #
381     def parse(date, now=self.now)
382       comp = !block_given?
383       d = Date._parse(date, comp)
384       year = d[:year]
385       year = yield(year) if year && !comp
386       make_time(date, year, d[:yday], d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
387     end
389     #
390     # Works similar to +parse+ except that instead of using a
391     # heuristic to detect the format of the input string, you provide
392     # a second argument that describes the format of the string.
393     #
394     # Raises `ArgumentError` if the date or format is invalid.
395     #
396     # If a block is given, the year described in +date+ is converted by the
397     # block.  For example:
398     #
399     #   Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
400     #
401     # Below is a list of the formatting options:
402     #
403     # %a :: The abbreviated weekday name ("Sun")
404     # %A :: The  full  weekday  name ("Sunday")
405     # %b :: The abbreviated month name ("Jan")
406     # %B :: The  full  month  name ("January")
407     # %c :: The preferred local date and time representation
408     # %C :: Century (20 in 2009)
409     # %d :: Day of the month (01..31)
410     # %D :: Date (%m/%d/%y)
411     # %e :: Day of the month, blank-padded ( 1..31)
412     # %F :: Equivalent to %Y-%m-%d (the ISO 8601 date format)
413     # %g :: The last two digits of the commercial year
414     # %G :: The week-based year according to ISO-8601 (week 1 starts on Monday
415     #       and includes January 4)
416     # %h :: Equivalent to %b
417     # %H :: Hour of the day, 24-hour clock (00..23)
418     # %I :: Hour of the day, 12-hour clock (01..12)
419     # %j :: Day of the year (001..366)
420     # %k :: hour, 24-hour clock, blank-padded ( 0..23)
421     # %l :: hour, 12-hour clock, blank-padded ( 0..12)
422     # %L :: Millisecond of the second (000..999)
423     # %m :: Month of the year (01..12)
424     # %M :: Minute of the hour (00..59)
425     # %n :: Newline (\n)
426     # %N :: Fractional seconds digits
427     # %p :: Meridian indicator ("AM" or "PM")
428     # %P :: Meridian indicator ("am" or "pm")
429     # %r :: time, 12-hour (same as %I:%M:%S %p)
430     # %R :: time, 24-hour (%H:%M)
431     # %s :: Number of seconds since 1970-01-01 00:00:00 UTC.
432     # %S :: Second of the minute (00..60)
433     # %t :: Tab character (\t)
434     # %T :: time, 24-hour (%H:%M:%S)
435     # %u :: Day of the week as a decimal, Monday being 1. (1..7)
436     # %U :: Week number of the current year, starting with the first Sunday as
437     #       the first day of the first week (00..53)
438     # %v :: VMS date (%e-%b-%Y)
439     # %V :: Week number of year according to ISO 8601 (01..53)
440     # %W :: Week  number  of the current year, starting with the first Monday
441     #       as the first day of the first week (00..53)
442     # %w :: Day of the week (Sunday is 0, 0..6)
443     # %x :: Preferred representation for the date alone, no time
444     # %X :: Preferred representation for the time alone, no date
445     # %y :: Year without a century (00..99)
446     # %Y :: Year which may include century, if provided
447     # %z :: Time zone as  hour offset from UTC (e.g. +0900)
448     # %Z :: Time zone name
449     # %% :: Literal "%" character
450     # %+ :: date(1) (%a %b %e %H:%M:%S %Z %Y)
451     #
452     #     require 'time'
453     #
454     #     Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
455     #
456     # You must require 'time' to use this method.
457     #
458     def strptime(date, format, now=self.now)
459       d = Date._strptime(date, format)
460       raise ArgumentError, "invalid date or strptime format - '#{date}' '#{format}'" unless d
461       if seconds = d[:seconds]
462         if sec_fraction = d[:sec_fraction]
463           usec = sec_fraction * 1000000
464           usec *= -1 if seconds < 0
465         else
466           usec = 0
467         end
468         t = Time.at(seconds, usec)
469         if zone = d[:zone]
470           force_zone!(t, zone)
471         end
472       else
473         year = d[:year]
474         year = yield(year) if year && block_given?
475         yday = d[:yday]
476         if (d[:cwyear] && !year) || ((d[:cwday] || d[:cweek]) && !(d[:mon] && d[:mday]))
477           # make_time doesn't deal with cwyear/cwday/cweek
478           return Date.strptime(date, format).to_time
479         end
480         if (d[:wnum0] || d[:wnum1]) && !yday && !(d[:mon] && d[:mday])
481           yday = Date.strptime(date, format).yday
482         end
483         t = make_time(date, year, yday, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
484       end
485       t
486     end
488     MonthValue = { # :nodoc:
489       'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
490       'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
491     }
493     #
494     # Parses +date+ as date-time defined by RFC 2822 and converts it to a Time
495     # object.  The format is identical to the date format defined by RFC 822 and
496     # updated by RFC 1123.
497     #
498     # ArgumentError is raised if +date+ is not compliant with RFC 2822
499     # or if the Time class cannot represent specified date.
500     #
501     # See #rfc2822 for more information on this format.
502     #
503     #     require 'time'
504     #
505     #     Time.rfc2822("Wed, 05 Oct 2011 22:26:12 -0400")
506     #     #=> 2010-10-05 22:26:12 -0400
507     #
508     # You must require 'time' to use this method.
509     #
510     def rfc2822(date)
511       if /\A\s*
512           (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
513           (\d{1,2})\s+
514           (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
515           (\d{2,})\s+
516           (\d{2})\s*
517           :\s*(\d{2})
518           (?:\s*:\s*(\d\d))?\s+
519           ([+-]\d{4}|
520            UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
521         # Since RFC 2822 permit comments, the regexp has no right anchor.
522         day = $1.to_i
523         mon = MonthValue[$2.upcase]
524         year = $3.to_i
525         short_year_p = $3.length <= 3
526         hour = $4.to_i
527         min = $5.to_i
528         sec = $6 ? $6.to_i : 0
529         zone = $7
531         if short_year_p
532           # following year completion is compliant with RFC 2822.
533           year = if year < 50
534                    2000 + year
535                  else
536                    1900 + year
537                  end
538         end
540         off = zone_offset(zone)
541         year, mon, day, hour, min, sec =
542           apply_offset(year, mon, day, hour, min, sec, off)
543         t = self.utc(year, mon, day, hour, min, sec)
544         force_zone!(t, zone, off)
545         t
546       else
547         raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
548       end
549     end
550     alias rfc822 rfc2822
552     #
553     # Parses +date+ as an HTTP-date defined by RFC 2616 and converts it to a
554     # Time object.
555     #
556     # ArgumentError is raised if +date+ is not compliant with RFC 2616 or if
557     # the Time class cannot represent specified date.
558     #
559     # See #httpdate for more information on this format.
560     #
561     #     require 'time'
562     #
563     #     Time.httpdate("Thu, 06 Oct 2011 02:26:12 GMT")
564     #     #=> 2011-10-06 02:26:12 UTC
565     #
566     # You must require 'time' to use this method.
567     #
568     def httpdate(date)
569       if date.match?(/\A\s*
570           (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
571           (\d{2})\x20
572           (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
573           (\d{4})\x20
574           (\d{2}):(\d{2}):(\d{2})\x20
575           GMT
576           \s*\z/ix)
577         self.rfc2822(date).utc
578       elsif /\A\s*
579              (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
580              (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
581              (\d\d):(\d\d):(\d\d)\x20
582              GMT
583              \s*\z/ix =~ date
584         year = $3.to_i
585         if year < 50
586           year += 2000
587         else
588           year += 1900
589         end
590         self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
591       elsif /\A\s*
592              (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
593              (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
594              (\d\d|\x20\d)\x20
595              (\d\d):(\d\d):(\d\d)\x20
596              (\d{4})
597              \s*\z/ix =~ date
598         self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
599                  $3.to_i, $4.to_i, $5.to_i)
600       else
601         raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
602       end
603     end
605     #
606     # Parses +time+ as a dateTime defined by the XML Schema and converts it to
607     # a Time object.  The format is a restricted version of the format defined
608     # by ISO 8601.
609     #
610     # ArgumentError is raised if +time+ is not compliant with the format or if
611     # the Time class cannot represent the specified time.
612     #
613     # See #xmlschema for more information on this format.
614     #
615     #     require 'time'
616     #
617     #     Time.xmlschema("2011-10-05T22:26:12-04:00")
618     #     #=> 2011-10-05 22:26:12-04:00
619     #
620     # You must require 'time' to use this method.
621     #
622     def xmlschema(time)
623       if /\A\s*
624           (-?\d+)-(\d\d)-(\d\d)
625           T
626           (\d\d):(\d\d):(\d\d)
627           (\.\d+)?
628           (Z|[+-]\d\d(?::?\d\d)?)?
629           \s*\z/ix =~ time
630         year = $1.to_i
631         mon = $2.to_i
632         day = $3.to_i
633         hour = $4.to_i
634         min = $5.to_i
635         sec = $6.to_i
636         usec = 0
637         if $7
638           usec = Rational($7) * 1000000
639         end
640         if $8
641           zone = $8
642           off = zone_offset(zone)
643           year, mon, day, hour, min, sec =
644             apply_offset(year, mon, day, hour, min, sec, off)
645           t = self.utc(year, mon, day, hour, min, sec, usec)
646           force_zone!(t, zone, off)
647           t
648         else
649           self.local(year, mon, day, hour, min, sec, usec)
650         end
651       else
652         raise ArgumentError.new("invalid xmlschema format: #{time.inspect}")
653       end
654     end
655     alias iso8601 xmlschema
656   end # class << self
658   #
659   # Returns a string which represents the time as date-time defined by RFC 2822:
660   #
661   #   day-of-week, DD month-name CCYY hh:mm:ss zone
662   #
663   # where zone is [+-]hhmm.
664   #
665   # If +self+ is a UTC time, -0000 is used as zone.
666   #
667   #     require 'time'
668   #
669   #     t = Time.now
670   #     t.rfc2822  # => "Wed, 05 Oct 2011 22:26:12 -0400"
671   #
672   # You must require 'time' to use this method.
673   #
674   def rfc2822
675     strftime('%a, %d %b %Y %T ') << (utc? ? '-0000' : strftime('%z'))
676   end
677   alias rfc822 rfc2822
679   #
680   # Returns a string which represents the time as RFC 1123 date of HTTP-date
681   # defined by RFC 2616:
682   #
683   #   day-of-week, DD month-name CCYY hh:mm:ss GMT
684   #
685   # Note that the result is always UTC (GMT).
686   #
687   #     require 'time'
688   #
689   #     t = Time.now
690   #     t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
691   #
692   # You must require 'time' to use this method.
693   #
694   def httpdate
695     getutc.strftime('%a, %d %b %Y %T GMT')
696   end
698   #
699   # Returns a string which represents the time as a dateTime defined by XML
700   # Schema:
701   #
702   #   CCYY-MM-DDThh:mm:ssTZD
703   #   CCYY-MM-DDThh:mm:ss.sssTZD
704   #
705   # where TZD is Z or [+-]hh:mm.
706   #
707   # If self is a UTC time, Z is used as TZD.  [+-]hh:mm is used otherwise.
708   #
709   # +fraction_digits+ specifies a number of digits to use for fractional
710   # seconds.  Its default value is 0.
711   #
712   #     require 'time'
713   #
714   #     t = Time.now
715   #     t.iso8601  # => "2011-10-05T22:26:12-04:00"
716   #
717   # You must require 'time' to use this method.
718   #
719   def xmlschema(fraction_digits=0)
720     fraction_digits = fraction_digits.to_i
721     s = strftime("%FT%T")
722     if fraction_digits > 0
723       s << strftime(".%#{fraction_digits}N")
724     end
725     s << (utc? ? 'Z' : strftime("%:z"))
726   end
727   alias iso8601 xmlschema