1 # frozen_string_literal: true
2 # shareable_constant_value: literal
10 # When 'time' is required, Time is extended with additional methods for parsing
11 # and converting Times.
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
29 VERSION = "0.4.1" # :nodoc:
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
38 ZoneOffset = { # :nodoc:
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,
57 # Return the number of seconds the specified time zone differs
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
65 # Textual time zones listed in ZoneOffset are also supported.
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.
73 # If +zone_offset+ is unable to determine the offset, nil will be
78 # Time.zone_offset("EST") #=> -18000
80 # You must require 'time' to use this method.
82 def zone_offset(zone, year=self.now.year)
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)
93 elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
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.
108 # GMT is used as a time zone abbreviation in Europe/London,
110 # So it is a local time.
113 # In RFC 2822, -0000 the date-time contains no information about the
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)
124 def force_zone!(t, zone, offset=nil)
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.
131 if t.utc_offset != offset
132 # Use the fixed offset timezone only if the local timezone cannot
133 # represent the given offset.
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:
145 if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
146 LeapYearMonthDays[m-1]
148 CommonYearMonthDays[m-1]
153 def apply_offset(year, mon, day, hour, min, sec, 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
164 days = month_days(year, mon)
165 if days and days < day
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
189 day = month_days(year, mon)
193 return year, mon, day, hour, min, sec
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}"
204 off_year = year || now.year
205 off = zone_offset(zone, off_year) if zone
209 unless (1..366) === yday
210 raise ArgumentError, "yday #{yday} out of range"
212 mon, day = (yday-1).divmod(31)
215 t = make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
217 return t if diff.zero?
219 if day > 28 and day > (mday = month_days(off_year, mon))
221 raise ArgumentError, "yday #{yday} out of range"
225 return make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
228 if now and now.respond_to?(:getlocal)
230 now = now.getlocal(off) if now.utc_offset != off
237 usec = sec_fraction * 1000000 if sec_fraction
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
261 off = zone_offset(zone, year) if zone
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)
271 self.local(year, mon, day, hour, min, sec, usec)
278 # Takes a string representation of a Time and attempts to parse it
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.
288 # Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
290 # Any missing pieces of the date are inferred based on the current date.
294 # # assuming the current date is "2011-10-31"
295 # Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500
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.
304 # attr_reader :mon, :day, :year
306 # def initialize(mon, day, year)
307 # @mon, @day, @year = mon, day, year
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)
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
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:
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
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:
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
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
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,
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.
368 # ArgumentError is raised if Date._parse cannot extract information from
369 # +date+ or if the Time class cannot represent specified date.
371 # This method can be used as a fail-safe for other parsing methods as:
373 # Time.rfc2822(date) rescue Time.parse(date)
374 # Time.httpdate(date) rescue Time.parse(date)
375 # Time.xmlschema(date) rescue Time.parse(date)
377 # A failure of Time.parse should be checked, though.
379 # You must require 'time' to use this method.
381 def parse(date, now=self.now)
383 d = Date._parse(date, comp)
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)
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.
394 # Raises ArgumentError if the date or format is invalid.
396 # If a block is given, the year described in +date+ is converted by the
397 # block. For example:
399 # Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
401 # Below is a list of the formatting options:
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)
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)
454 # Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
456 # You must require 'time' to use this method.
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
468 t = Time.at(seconds, usec)
474 year = yield(year) if year && block_given?
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
480 if (d[:wnum0] || d[:wnum1]) && !yday && !(d[:mon] && d[:mday])
481 yday = Date.strptime(date, format).yday
483 t = make_time(date, year, yday, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
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
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.
498 # ArgumentError is raised if +date+ is not compliant with RFC 2822
499 # or if the Time class cannot represent specified date.
501 # See #rfc2822 for more information on this format.
505 # Time.rfc2822("Wed, 05 Oct 2011 22:26:12 -0400")
506 # #=> 2010-10-05 22:26:12 -0400
508 # You must require 'time' to use this method.
512 (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
514 (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
518 (?:\s*:\s*(\d\d))?\s+
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.
523 mon = MonthValue[$2.upcase]
525 short_year_p = $3.length <= 3
528 sec = $6 ? $6.to_i : 0
532 # following year completion is compliant with RFC 2822.
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)
547 raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
553 # Parses +date+ as an HTTP-date defined by RFC 2616 and converts it to a
556 # ArgumentError is raised if +date+ is not compliant with RFC 2616 or if
557 # the Time class cannot represent specified date.
559 # See #httpdate for more information on this format.
563 # Time.httpdate("Thu, 06 Oct 2011 02:26:12 GMT")
564 # #=> 2011-10-06 02:26:12 UTC
566 # You must require 'time' to use this method.
569 if date.match?(/\A\s*
570 (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
572 (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
574 (\d{2}):(\d{2}):(\d{2})\x20
577 self.rfc2822(date).utc
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
590 self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
592 (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
593 (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
595 (\d\d):(\d\d):(\d\d)\x20
598 self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
599 $3.to_i, $4.to_i, $5.to_i)
601 raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
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
610 # ArgumentError is raised if +time+ is not compliant with the format or if
611 # the Time class cannot represent the specified time.
613 # See #xmlschema for more information on this format.
617 # Time.xmlschema("2011-10-05T22:26:12-04:00")
618 # #=> 2011-10-05 22:26:12-04:00
620 # You must require 'time' to use this method.
624 (-?\d+)-(\d\d)-(\d\d)
628 (Z|[+-]\d\d(?::?\d\d)?)?
638 usec = Rational($7) * 1000000
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)
649 self.local(year, mon, day, hour, min, sec, usec)
652 raise ArgumentError.new("invalid xmlschema format: #{time.inspect}")
655 alias iso8601 xmlschema
659 # Returns a string which represents the time as date-time defined by RFC 2822:
661 # day-of-week, DD month-name CCYY hh:mm:ss zone
663 # where zone is [+-]hhmm.
665 # If +self+ is a UTC time, -0000 is used as zone.
670 # t.rfc2822 # => "Wed, 05 Oct 2011 22:26:12 -0400"
672 # You must require 'time' to use this method.
675 strftime('%a, %d %b %Y %T ') << (utc? ? '-0000' : strftime('%z'))
680 # Returns a string which represents the time as RFC 1123 date of HTTP-date
681 # defined by RFC 2616:
683 # day-of-week, DD month-name CCYY hh:mm:ss GMT
685 # Note that the result is always UTC (GMT).
690 # t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
692 # You must require 'time' to use this method.
695 getutc.strftime('%a, %d %b %Y %T GMT')
698 unless method_defined?(:xmlschema)
700 # Returns a string which represents the time as a dateTime defined by XML
703 # CCYY-MM-DDThh:mm:ssTZD
704 # CCYY-MM-DDThh:mm:ss.sssTZD
706 # where TZD is Z or [+-]hh:mm.
708 # If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
710 # +fraction_digits+ specifies a number of digits to use for fractional
711 # seconds. Its default value is 0.
716 # t.iso8601 # => "2011-10-05T22:26:12-04:00"
718 # You must require 'time' to use this method.
720 def xmlschema(fraction_digits=0)
721 fraction_digits = fraction_digits.to_i
722 s = strftime("%FT%T")
723 if fraction_digits > 0
724 s << strftime(".%#{fraction_digits}N")
726 s << (utc? ? 'Z' : strftime("%:z"))
729 alias iso8601 xmlschema unless method_defined?(:iso8601)