# This library extends the Time class:
# * conversion between date string and time object.
# * date-time defined by RFC 2822
# * HTTP-date defined by RFC 2616
# * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
# * various formats handled by Date._parse (string to time only)
# === Specialized interface
# This library provides methods dedicated to special purposes:
# * RFC 2822, RFC 2616 and XML Schema.
# * They makes usual life easier.
# === Doesn't depend on strftime
# This library doesn't use +strftime+. Especially #rfc2822 doesn't depend
# * %a and %b are locale sensitive
# Since they are locale sensitive, they may be replaced to
# invalid weekday/month name in some locales.
# Since ruby-1.6 doesn't invoke setlocale by default,
# the problem doesn't arise until some external library invokes setlocale.
# Ruby/GTK is the example of such library.
# %z is required to generate zone in date-time of RFC 2822
# but it is not portable.
# == Revision Information
# Implements the extensions to the Time class that are described in the
# documentation for the time.rb library.
'EST' => -5, 'EDT' => -4,
'CST' => -6, 'CDT' => -5,
'MST' => -7, 'MDT' => -6,
'PST' => -8, 'PDT' => -7,
# Following definition of military zones is original one.
# See RFC 1123 and RFC 2822 for the error in RFC 822.
'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6,
'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6,
'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
def zone_offset(zone, year=self.now.year)
if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone
off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
elsif /\A[+-]\d\d\z/ =~ zone
elsif ZoneOffset.include?(zone)
off = ZoneOffset[zone] * 3600
elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
# * +0000 means localtime. [RFC 2822]
# * GMT is a localtime abbreviation in Europe/London, etc.
if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone
LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
def apply_offset(year, mon, day, hour, min, sec, off)
if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
if o != 0 then min += o; o, min = min.divmod(60); off += o end
if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
if month_days(year, mon) < day
if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
day = month_days(year, mon)
return year, mon, day, hour, min, sec
def make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now)
usec = (sec_fraction * 1000000).to_i if sec_fraction
break if year; year = now.year
break if mon; mon = now.mon
break if day; day = now.day
break if hour; hour = now.hour
break if min; min = now.min
break if sec; sec = now.sec
break if sec_fraction; usec = now.tv_usec
off = zone_offset(zone, year) if zone
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, off)
t = self.utc(year, mon, day, hour, min, sec, usec)
t.localtime if !zone_utc?(zone)
self.local(year, mon, day, hour, min, sec, usec)
# Parses +date+ using Date._parse and converts it to a Time object.
# If a block is given, the year described in +date+ is converted by the
# Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
# If the upper components of the given time are broken or missing, they are
# supplied with those of +now+. For the lower components, the minimum
# values (1 or 0) are assumed if broken or missing. For example:
# # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
# # your timezone is GMT:
# Time.parse("16:30") #=> Thu Nov 29 16:30:00 GMT 2001
# Time.parse("7/23") #=> Mon Jul 23 00:00:00 GMT 2001
# Time.parse("Aug 31") #=> Fri Aug 31 00:00:00 GMT 2001
# Since there are numerous conflicts among locally defined timezone
# abbreviations all over the world, this method is not made to
# understand all of them. For example, the abbreviation "CST" is
# -06:00 in America/Chicago,
# -05:00 in America/Havana,
# +09:30 in Australia/Darwin,
# +10:30 in Australia/Adelaide,
# Based on the fact, this method only understands the timezone
# abbreviations described in RFC 822 and the system timezone, in the
# order named. (i.e. a definition in RFC 822 overrides the system
# timezone definition.) The system timezone is taken from
# <tt>Time.local(year, 1, 1).zone</tt> and
# <tt>Time.local(year, 7, 1).zone</tt>.
# If the extracted timezone abbreviation does not match any of them,
# it is ignored and the given time is regarded as a local time.
# ArgumentError is raised if Date._parse cannot extract information from
# +date+ or Time class cannot represent specified date.
# This method can be used as fail-safe for other parsing methods as:
# Time.rfc2822(date) rescue Time.parse(date)
# Time.httpdate(date) rescue Time.parse(date)
# Time.xmlschema(date) rescue Time.parse(date)
# A failure for Time.parse should be checked, though.
def parse(date, now=self.now)
d = Date._parse(date, false)
year = yield(year) if year && block_given?
make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
# Parses +date+ as date-time defined by RFC 2822 and converts it to a Time
# object. The format is identical to the date format defined by RFC 822 and
# ArgumentError is raised if +date+ is not compliant with RFC 2822
# or Time class cannot represent specified date.
# See #rfc2822 for more information on this format.
(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
# Since RFC 2822 permit comments, the regexp has no right anchor.
mon = MonthValue[$2.upcase]
# following year completion is compliant with RFC 2822.
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
t = self.utc(year, mon, day, hour, min, sec)
t.localtime if !zone_utc?(zone)
raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
# Parses +date+ as HTTP-date defined by RFC 2616 and converts it to a Time
# ArgumentError is raised if +date+ is not compliant with RFC 2616 or Time
# class cannot represent specified date.
# See #httpdate for more information on this format.
(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
(\d{2}):(\d{2}):(\d{2})\x20
(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
(\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
$3.to_i, $4.to_i, $5.to_i)
raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
# Parses +date+ as dateTime defined by XML Schema and converts it to a Time
# object. The format is restricted version of the format defined by ISO
# ArgumentError is raised if +date+ is not compliant with the format or Time
# class cannot represent specified date.
# See #xmlschema for more information on this format.
usec = ($7[1..-1] + '000000')[0,6].to_i if $7
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
self.utc(year, mon, day, hour, min, sec, usec)
self.local(year, mon, day, hour, min, sec, usec)
raise ArgumentError.new("invalid date: #{date.inspect}")
# Returns a string which represents the time as date-time defined by RFC 2822:
# day-of-week, DD month-name CCYY hh:mm:ss zone
# where zone is [+-]hhmm.
# If +self+ is a UTC time, -0000 is used as zone.
sprintf('%s, %02d %s %d %02d:%02d:%02d ',
day, RFC2822_MONTH_NAME[mon-1], year,
sign = off < 0 ? '-' : '+'
sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
# Returns a string which represents the time as rfc1123-date of HTTP-date
# day-of-week, DD month-name CCYY hh:mm:ss GMT
# Note that the result is always UTC (GMT).
sprintf('%s, %02d %s %d %02d:%02d:%02d GMT',
RFC2822_DAY_NAME[t.wday],
t.day, RFC2822_MONTH_NAME[t.mon-1], t.year,
# Returns a string which represents the time as dateTime defined by XML
# CCYY-MM-DDThh:mm:ss.sssTZD
# where TZD is Z or [+-]hh:mm.
# If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
# +fractional_seconds+ specifies a number of digits of fractional seconds.
# Its default value is 0.
def xmlschema(fraction_digits=0)
sprintf('%d-%02d-%02dT%02d:%02d:%02d',
year, mon, day, hour, min, sec) +
elsif fraction_digits <= 6
'.' + sprintf('%06d', usec)[0, fraction_digits]
'.' + sprintf('%06d', usec) + '0' * (fraction_digits - 6)
sign = off < 0 ? '-' : '+'
sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
class TimeExtentionTest < Test::Unit::TestCase # :nodoc:
assert_equal(Time.utc(1976, 8, 26, 14, 30) + 4 * 3600,
Time.rfc2822("26 Aug 76 14:30 EDT"))
assert_equal(Time.utc(1976, 8, 27, 9, 32) + 7 * 3600,
Time.rfc2822("27 Aug 76 09:32 PDT"))
assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600,
Time.rfc2822("Fri, 21 Nov 1997 09:55:06 -0600"))
assert_equal(Time.utc(2003, 7, 1, 10, 52, 37) - 2 * 3600,
Time.rfc2822("Tue, 1 Jul 2003 10:52:37 +0200"))
assert_equal(Time.utc(1997, 11, 21, 10, 1, 10) + 6 * 3600,
Time.rfc2822("Fri, 21 Nov 1997 10:01:10 -0600"))
assert_equal(Time.utc(1997, 11, 21, 11, 0, 0) + 6 * 3600,
Time.rfc2822("Fri, 21 Nov 1997 11:00:00 -0600"))
assert_equal(Time.utc(1997, 11, 24, 14, 22, 1) + 8 * 3600,
Time.rfc2822("Mon, 24 Nov 1997 14:22:01 -0800"))
assert_equal(Time.utc(1969, 2, 13, 23, 32, 54) + 3 * 3600 + 30 * 60,
Time.rfc2822("Thu, 13 Feb 1969 23:32:54 -0330"))
assert_equal(Time.utc(1969, 2, 13, 23, 32, 0) + 3 * 3600 + 30 * 60,
-0330 (Newfoundland Time)"))