Extended maintenance of Ruby versions 1.8.7 and 1.9.2 ended on July 31, 2014. Read more

In Files

  • date.rb
  • date/format.rb

Class/Module Index [+]

Quicksearch

Date

Class representing a date.

See the documentation to the file date.rb for an overview.

Internally, the date is represented as an Astronomical Julian Day Number, ajd. The Day of Calendar Reform, sg, is also stored, for conversions to other date formats. (There is also an of field for a time zone offset, but this is only for the use of the DateTime subclass.)

A new Date object is created using one of the object creation class methods named after the corresponding date format, and the arguments appropriate to that date format; for instance, ::civil (aliased to ::new) with year, month, and day-of-month, or ::ordinal with year and day-of-year. All of these object creation class methods also take the Day of Calendar Reform as an optional argument.

Date objects are immutable once created.

Once a Date has been created, date values can be retrieved for the different date formats supported using instance methods. For instance, mon() gives the Civil month, cwday() gives the Commercial day of the week, and yday() gives the Ordinal day of the year. Date values can be retrieved in any format, regardless of what format was used to create the Date instance.

The Date class includes the Comparable module, allowing date objects to be compared and sorted, ranges of dates to be created, and so forth.

Constants

ABBR_DAYNAMES

Abbreviated day names, in English.

ABBR_MONTHNAMES

Abbreviated month names, in English.

DAYNAMES

Full names of days of the week, in English. Days of the week count from 0 to 6 (except in the commercial week); a day’s numerical representation indexed into this array gives the name of that day.

ENGLAND

The Julian Day Number of the Day of Calendar Reform for England and her Colonies.

GREGORIAN

A constant used to indicate that a Date should always use the Gregorian calendar.

ITALY

The Julian Day Number of the Day of Calendar Reform for Italy and the Catholic countries.

JULIAN

A constant used to indicate that a Date should always use the Julian calendar.

MONTHNAMES

Full month names, in English. Months count from 1 to 12; a month’s numerical representation indexed into this array gives the name of that month (hence the first element is nil).

Public Class Methods

_parse(str, comp=false) click to toggle source
 
               # File date/format.rb, line 1054
def self._parse(str, comp=false)
  str = str.dup

  e = Format::Bag.new

  e._comp = comp

  str.gsub!(/[^-+',.\/:@[:alnum:]\[\]\x80-\xff]+/n, ' ')

  _parse_time(str, e) # || _parse_beat(str, e)
  _parse_day(str, e)

  _parse_eu(str, e)     ||
  _parse_us(str, e)     ||
  _parse_iso(str, e)    ||
  _parse_jis(str, e)    ||
  _parse_vms(str, e)    ||
  _parse_sla(str, e)    ||
  _parse_dot(str, e)    ||
  _parse_iso2(str, e)   ||
  _parse_year(str, e)   ||
  _parse_mon(str, e)    ||
  _parse_mday(str, e)   ||
  _parse_ddd(str, e)

  if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/in, ' ')
    if e.year
      e.year = -e.year + 1
    end
  end

  if str.sub!(/\A\s*(\d{1,2})\s*\z/n, ' ')
    if e.hour && !e.mday
      v = $1.to_i
      if (1..31) === v
        e.mday = v
      end
    end
    if e.mday && !e.hour
      v = $1.to_i
      if (0..24) === v
        e.hour = v
      end
    end
  end

  if e._comp
    if e.cwyear
      if e.cwyear >= 0 && e.cwyear <= 99
        e.cwyear += if e.cwyear >= 69
                    then 1900 else 2000 end
      end
    end
    if e.year
      if e.year >= 0 && e.year <= 99
        e.year += if e.year >= 69
                  then 1900 else 2000 end
      end
    end
  end

  e.offset ||= zone_to_diff(e.zone) if e.zone

  e.to_hash
end
            
_strptime(str, fmt='%F') click to toggle source
 
               # File date/format.rb, line 598
def self._strptime(str, fmt='%F')
  str = str.dup
  e = Format::Bag.new
  return unless _strptime_i(str, fmt, e)

  if e._cent
    if e.cwyear
      e.cwyear += e._cent * 100
    end
    if e.year
      e.  year += e._cent * 100
    end
  end

  if e._merid
    if e.hour
      e.hour = 12
      e.hour += e._merid
    end
  end

  unless str.empty?
    e.leftover = str
  end

  e.to_hash
end
            
ajd_to_amjd(ajd) click to toggle source

Convert an Astronomical Julian Day Number to an Astronomical Modified Julian Day Number.

 
               # File date.rb, line 538
def self.ajd_to_amjd(ajd) ajd - MJD_EPOCH_IN_AJD end
            
ajd_to_jd(ajd, of=0) click to toggle source

Convert an Astronomical Julian Day Number to a (civil) Julian Day Number.

ajd is the Astronomical Julian Day Number to convert. of is the offset from UTC as a fraction of a day (defaults to 0).

Returns the (civil) Julian Day Number as [day_number, fraction] where fraction is always 1/2.

 
               # File date.rb, line 492
def self.ajd_to_jd(ajd, of=0) (ajd + of + HALF_DAYS_IN_DAY).divmod(1) end
            
amjd_to_ajd(amjd) click to toggle source

Convert an Astronomical Modified Julian Day Number to an Astronomical Julian Day Number.

 
               # File date.rb, line 534
def self.amjd_to_ajd(amjd) amjd + MJD_EPOCH_IN_AJD end
            
civil(y=-4712, m=1, d=1, sg=ITALY) click to toggle source

Create a new Date object for the Civil Date specified by year y, month m, and day-of-month d.

m and d can be negative, in which case they count backwards from the end of the year and the end of the month respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. can be negative

y defaults to -4712, m to 1, and d to 1; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 750
def self.civil(y=-4712, m=1, d=1, sg=ITALY)
  unless jd = valid_civil?(y, m, d, sg)
    raise ArgumentError, 'invalid date'
  end
  new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
            
Also aliased as: new
civil_to_jd(y, m, d, sg=GREGORIAN) click to toggle source

Convert a Civil Date to a Julian Day Number. y, m, and d are the year, month, and day of the month. sg specifies the Day of Calendar Reform.

Returns the corresponding Julian Day Number.

 
               # File date.rb, line 396
def self.civil_to_jd(y, m, d, sg=GREGORIAN)
  if m <= 2
    y -= 1
    m += 12
  end
  a = (y / 100.0).floor
  b = 2 - a + (a / 4.0).floor
  jd = (365.25 * (y + 4716)).floor +
    (30.6001 * (m + 1)).floor +
    d + b - 1524
  if julian?(jd, sg)
    jd -= b
  end
  jd
end
            
commercial(y=1582, w=41, d=5, sg=ITALY) click to toggle source

Create a new Date object for the Commercial Date specified by year y, week-of-year w, and day-of-week d.

Monday is day-of-week 1; Sunday is day-of-week 7.

w and d can be negative, in which case they count backwards from the end of the year and the end of the week respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised.

y defaults to 1582, w to 41, and d to 5, the Day of Calendar Reform for Italy and the Catholic countries.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 773
def self.commercial(y=1582, w=41, d=5, sg=ITALY)
  unless jd = valid_commercial?(y, w, d, sg)
    raise ArgumentError, 'invalid date'
  end
  new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
            
commercial_to_jd(y, w, d, ns=GREGORIAN) click to toggle source

Convert a Commercial Date to a Julian Day Number.

y, w, and d are the (commercial) year, week of the year, and day of the week of the Commercial Date to convert. sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 445
def self.commercial_to_jd(y, w, d, ns=GREGORIAN)
  jd = civil_to_jd(y, 1, 4, ns)
  (jd - (((jd - 1) + 1) % 7)) +
    7 * (w - 1) +
    (d - 1)
end
            
day_fraction_to_time(fr) click to toggle source

Convert a fractional day fr to [hours, minutes, seconds, fraction_of_a_second]

 
               # File date.rb, line 507
def self.day_fraction_to_time(fr)
  ss,  fr = fr.divmod(SECONDS_IN_DAY) # 4p
  h,   ss = ss.divmod(3600)
  min, s  = ss.divmod(60)
  return h, min, s, fr
end
            
gregorian?(jd, sg) click to toggle source

Does a given Julian Day Number fall inside the new-style (Gregorian) calendar?

The reverse of self.os? See the documentation for that method for more details.

 
               # File date.rb, line 358
def self.gregorian? (jd, sg) !julian?(jd, sg) end
            
gregorian_leap?(y) click to toggle source

Is a year a leap year in the Gregorian calendar?

All years divisible by 4 are leap years in the Gregorian calendar, except for years divisible by 100 and not by 400.

 
               # File date.rb, line 570
def self.gregorian_leap? (y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0 end
            
Also aliased as: leap?
jd(jd=0, sg=ITALY) click to toggle source

Create a new Date object from a Julian Day Number.

jd is the Julian Day Number; if not specified, it defaults to 0. sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 715
def self.jd(jd=0, sg=ITALY)
  jd = valid_jd?(jd, sg)
  new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
            
jd_to_ajd(jd, fr, of=0) click to toggle source

Convert a (civil) Julian Day Number to an Astronomical Julian Day Number.

jd is the Julian Day Number to convert, and fr is a fractional day. of is the offset from UTC as a fraction of a day (defaults to 0).

Returns the Astronomical Julian Day Number as a single numeric value.

 
               # File date.rb, line 503
def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - HALF_DAYS_IN_DAY end
            
jd_to_civil(jd, sg=GREGORIAN) click to toggle source

Convert a Julian Day Number to a Civil Date. jd is the Julian Day Number. sg specifies the Day of Calendar Reform.

Returns the corresponding [year, month, day_of_month] as a three-element array.

 
               # File date.rb, line 418
def self.jd_to_civil(jd, sg=GREGORIAN)
  if julian?(jd, sg)
    a = jd
  else
    x = ((jd - 1867216.25) / 36524.25).floor
    a = jd + 1 + x - (x / 4.0).floor
  end
  b = a + 1524
  c = ((b - 122.1) / 365.25).floor
  d = (365.25 * c).floor
  e = ((b - d) / 30.6001).floor
  dom = b - d - (30.6001 * e).floor
  if e <= 13
    m = e - 1
    y = c - 4716
  else
    m = e - 13
    y = c - 4715
  end
  return y, m, dom
end
            
jd_to_commercial(jd, sg=GREGORIAN) click to toggle source

Convert a Julian Day Number to a Commercial Date

jd is the Julian Day Number to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Commercial Date as

commercial_year, week_of_year, day_of_week
 
               # File date.rb, line 459
def self.jd_to_commercial(jd, sg=GREGORIAN)
  ns = fix_style(jd, sg)
  a = jd_to_civil(jd - 3, ns)[0]
  y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end
  w = 1 + ((jd - commercial_to_jd(y, 1, 1, ns)) / 7).floor
  d = (jd + 1) % 7
  d = 7 if d == 0
  return y, w, d
end
            
jd_to_ld(jd) click to toggle source

Convert a Julian Day Number to the number of days since the adoption of the Gregorian Calendar (in Italy).

 
               # File date.rb, line 554
def self.jd_to_ld(jd) jd - LD_EPOCH_IN_CJD end
            
jd_to_mjd(jd) click to toggle source

Convert a Julian Day Number to a Modified Julian Day Number.

 
               # File date.rb, line 546
def self.jd_to_mjd(jd) jd - MJD_EPOCH_IN_CJD end
            
jd_to_ordinal(jd, sg=GREGORIAN) click to toggle source

Convert a Julian Day Number to an Ordinal Date.

jd is the Julian Day Number to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Ordinal Date as

year, day_of_year
 
               # File date.rb, line 385
def self.jd_to_ordinal(jd, sg=GREGORIAN)
  y = jd_to_civil(jd, sg)[0]
  doy = jd - civil_to_jd(y - 1, 12, 31, fix_style(jd, sg))
  return y, doy
end
            
jd_to_wday(jd) click to toggle source

Convert a Julian Day Number to the day of the week.

Sunday is day-of-week 0; Saturday is day-of-week 6.

 
               # File date.rb, line 559
def self.jd_to_wday(jd) (jd + 1) % 7 end
            
julian?(jd, sg) click to toggle source

Does a given Julian Day Number fall inside the old-style (Julian) calendar?

jd is the Julian Day Number in question. sg may be Date::GREGORIAN, in which case the answer is false; it may be Date::JULIAN, in which case the answer is true; or it may a number representing the Day of Calendar Reform. Date::ENGLAND and Date::ITALY are two possible such days.

 
               # File date.rb, line 340
def self.julian? (jd, sg)
  case sg
  when Numeric
    jd < sg
  else
    if $VERBOSE
      warn("#{caller.shift.sub(/:in .*/, '')}: "  "warning: do not use non-numerical object as julian day number anymore")
    end
    not sg
  end
end
            
julian_leap?(y) click to toggle source

Is a year a leap year in the Julian calendar?

All years divisible by 4 are leap years in the Julian calendar.

 
               # File date.rb, line 564
def self.julian_leap? (y) y % 4 == 0 end
            
ld_to_jd(ld) click to toggle source

Convert a count of the number of days since the adoption of the Gregorian Calendar (in Italy) to a Julian Day Number.

 
               # File date.rb, line 550
def self.ld_to_jd(ld) ld + LD_EPOCH_IN_CJD end
            
leap?(y) click to toggle source
Alias for: gregorian_leap?
mjd_to_jd(mjd) click to toggle source

Convert a Modified Julian Day Number to a Julian Day Number.

 
               # File date.rb, line 542
def self.mjd_to_jd(mjd) mjd + MJD_EPOCH_IN_CJD end
            
new(y=-4712, m=1, d=1, sg=ITALY) click to toggle source
Also aliased as: new!
Alias for: civil
new(ajd=0, of=0, sg=ITALY) click to toggle source

NOTE this is the documentation for the method new!(). If you are reading this as the documentation for new(), that is because rdoc doesn't fully support the aliasing of the initialize() method. new() is in fact an alias for civil(): read the documentation for that method instead.

Create a new Date object.

ajd is the Astronomical Julian Day Number. of is the offset from UTC as a fraction of a day. Both default to 0.

sg specifies the Day of Calendar Reform to use for this Date object.

Using one of the factory methods such as ::civil is generally easier and safer.

 
               # File date.rb, line 1040
def initialize(ajd=0, of=0, sg=ITALY) @ajd, @of, @sg = ajd, of, sg end
            
new!(y=-4712, m=1, d=1, sg=ITALY) click to toggle source
Alias for: new
ordinal(y=-4712, d=1, sg=ITALY) click to toggle source

Create a new Date object from an Ordinal Date, specified by year y and day-of-year d. d can be negative, in which it counts backwards from the end of the year. No year wraparound is performed, however. An invalid value for d results in an ArgumentError being raised.

y defaults to -4712, and d to 1; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 730
def self.ordinal(y=-4712, d=1, sg=ITALY)
  unless jd = valid_ordinal?(y, d, sg)
    raise ArgumentError, 'invalid date'
  end
  new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
            
ordinal_to_jd(y, d, sg=GREGORIAN) click to toggle source

Convert an Ordinal Date to a Julian Day Number.

y and d are the year and day-of-year to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Julian Day Number.

 
               # File date.rb, line 374
def self.ordinal_to_jd(y, d, sg=GREGORIAN)
  civil_to_jd(y, 1, d, sg)
end
            
parse(str='-4712-01-01', comp=false, sg=ITALY) click to toggle source

Create a new Date object by parsing from a String, without specifying the format.

str is a String holding a date representation. comp specifies whether to interpret 2-digit years as 19XX (>= 69) or 20XX (< 69); the default is not to. The method will attempt to parse a date from the String using various heuristics; see #_parse in date/format.rb for more details. If parsing fails, an ArgumentError will be raised.

The default str is ‘-4712-01-01’; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 998
def self.parse(str='-4712-01-01', comp=false, sg=ITALY)
  elem = _parse(str, comp)
  new_by_frags(elem, sg)
end
            
strptime(str='-4712-01-01', fmt='%F', sg=ITALY) click to toggle source

Create a new Date object by parsing from a String according to a specified format.

str is a String holding a date representation. fmt is the format that the date is in. See date/format.rb for details on supported formats.

The default str is ‘-4712-01-01’, and the default fmt is ‘%F’, which means Year-Month-Day_of_Month. This gives Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

An ArgumentError will be raised if str cannot be parsed.

 
               # File date.rb, line 978
def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY)
  elem = _strptime(str, fmt)
  new_by_frags(elem, sg)
end
            
time_to_day_fraction(h, min, s) click to toggle source
 
               # File date.rb, line 519
def self.time_to_day_fraction(h, min, s)
  Rational(h * 3600 + min * 60 + s, 86400) # 4p
end
            
valid_civil?(y, m, d, sg=ITALY) click to toggle source

Do year y, month m, and day-of-month d make a valid Civil Date? Returns the corresponding Julian Day Number if they do, nil if they don’t.

m and d can be negative, in which case they count backwards from the end of the year and the end of the month respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 620
def self.valid_civil? (y, m, d, sg=ITALY)
  if m < 0
    m += 13
  end
  if d < 0
    ny, nm = (y * 12 + m).divmod(12)
    nm,    = (nm + 1).divmod(1)
    jd = civil_to_jd(ny, nm, d + 1, sg)
    ns = fix_style(jd, sg)
    return unless [y, m] == jd_to_civil(jd, sg)[0..1]
    return unless [ny, nm, 1] == jd_to_civil(jd - d, ns)
  else
    jd = civil_to_jd(y, m, d, sg)
    return unless [y, m, d] == jd_to_civil(jd, sg)
  end
  jd
end
            
Also aliased as: valid_date?
valid_commercial?(y, w, d, sg=ITALY) click to toggle source

Do year y, week-of-year w, and day-of-week d make a valid Commercial Date? Returns the corresponding Julian Day Number if they do, nil if they don’t.

Monday is day-of-week 1; Sunday is day-of-week 7.

w and d can be negative, in which case they count backwards from the end of the year and the end of the week respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 654
def self.valid_commercial? (y, w, d, sg=ITALY)
  if d < 0
    d += 8
  end
  if w < 0
    ny, nw, nd =
      jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)
    return unless ny == y
    w = nw
  end
  jd = commercial_to_jd(y, w, d)
  return unless gregorian?(jd, sg)
  return unless [y, w, d] == jd_to_commercial(jd)
  jd
end
            
valid_date?(y, m, d, sg=ITALY) click to toggle source
Alias for: valid_civil?
valid_jd?(jd, sg=ITALY) click to toggle source

Is jd a valid Julian Day Number?

If it is, returns it. In fact, any value is treated as a valid Julian Day Number.

 
               # File date.rb, line 579
def self.valid_jd? (jd, sg=ITALY) jd end
            
valid_ordinal?(y, d, sg=ITALY) click to toggle source

Do the year y and day-of-year d make a valid Ordinal Date? Returns the corresponding Julian Day Number if they do, or nil if they don’t.

d can be a negative number, in which case it counts backwards from the end of the year (-1 being the last day of the year). No year wraparound is performed, however, so valid values of d are -365 .. -1, 1 .. 365 on a non-leap-year, -366 .. -1, 1 .. 366 on a leap year. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

 
               # File date.rb, line 594
def self.valid_ordinal? (y, d, sg=ITALY)
  if d < 0
    ny, = (y + 1).divmod(1)
    jd = ordinal_to_jd(ny, d + 1, sg)
    ns = fix_style(jd, sg)
    return unless [y] == jd_to_ordinal(jd, sg)[0..0]
    return unless [ny, 1] == jd_to_ordinal(jd - d, ns)
  else
    jd = ordinal_to_jd(y, d, sg)
    return unless [y, d] == jd_to_ordinal(jd, sg)
  end
  jd
end
            
valid_time?(h, min, s) click to toggle source

Do hour h, minute min, and second s constitute a valid time?

If they do, returns their value as a fraction of a day. If not, returns nil.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed.

 
               # File date.rb, line 697
def self.valid_time? (h, min, s)
  h   += 24 if h   < 0
  min += 60 if min < 0
  s   += 60 if s   < 0
  return unless ((0...24) === h &&
                 (0...60) === min &&
                 (0...60) === s) ||
                (24 == h &&
                  0 == min &&
                  0 == s)
  time_to_day_fraction(h, min, s)
end
            

Public Instance Methods

ajd() click to toggle source

Get the date as an Astronomical Julian Day Number.

 
               # File date.rb, line 1043
def ajd() @ajd end
            
amjd() click to toggle source

Get the date as an Astronomical Modified Julian Day Number.

 
               # File date.rb, line 1046
def amjd() self.class.ajd_to_amjd(@ajd) end
            
asctime() click to toggle source

alias_method :format, :strftime

 
               # File date/format.rb, line 352
def asctime() strftime('%c') end
            
Also aliased as: ctime
ctime() click to toggle source
Alias for: asctime
day_fraction() click to toggle source

Get any fractional day part of the date.

 
               # File date.rb, line 1054
def day_fraction() self.class.ajd_to_jd(@ajd, @of)[1] end
            
jd() click to toggle source

Get the date as a Julian Day Number.

 
               # File date.rb, line 1051
def jd() self.class.ajd_to_jd(@ajd, @of)[0] end
            
ld() click to toggle source

Get the date as the number of days since the Day of Calendar Reform (in Italy and the Catholic countries).

 
               # File date.rb, line 1061
def ld() self.class.jd_to_ld(jd) end
            
mjd() click to toggle source

Get the date as a Modified Julian Day Number.

 
               # File date.rb, line 1057
def mjd() self.class.jd_to_mjd(jd) end
            
strftime(fmt='%F') click to toggle source
 
               # File date/format.rb, line 217
def strftime(fmt='%F')
  fmt.gsub(/%([-_0^#]+)?(\d+)?([EO]?(?::{1,3}z|.))/m) do |m|
    f = {}
    a = $&
    s, w, c = $1, $2, $3
    if s
      s.scan(/./) do |k|
        case k
        when '-'; f[:p] = '-'
        when '_'; f[:p] = "\s"
        when '0'; f[:p] = '0'
        when '^'; f[:u] = true
        when '#'; f[:x] = true
        end
      end
    end
    if w
      f[:w] = w.to_i
    end
    case c
    when 'A'; emit_ad(DAYNAMES[wday], 0, f)
    when 'a'; emit_ad(ABBR_DAYNAMES[wday], 0, f)
    when 'B'; emit_ad(MONTHNAMES[mon], 0, f)
    when 'b'; emit_ad(ABBR_MONTHNAMES[mon], 0, f)
    when 'C', 'EC'; emit_sn((year / 100).floor, 2, f)
    when 'c', 'Ec'; emit_a(strftime('%a %b %e %H:%M:%S %Y'), 0, f)
    when 'D'; emit_a(strftime('%m/%d/%y'), 0, f)
    when 'd', 'Od'; emit_n(mday, 2, f)
    when 'e', 'Oe'; emit_a(mday, 2, f)
    when 'F'
      if m == '%F'
        format('%.4d-%02d-%02d', year, mon, mday) # 4p
      else
        emit_a(strftime('%Y-%m-%d'), 0, f)
      end
    when 'G'; emit_sn(cwyear, 4, f)
    when 'g'; emit_n(cwyear % 100, 2, f)
    when 'H', 'OH'; emit_n(hour, 2, f)
    when 'h'; emit_ad(strftime('%b'), 0, f)
    when 'I', 'OI'; emit_n((hour % 12).nonzero? || 12, 2, f)
    when 'j'; emit_n(yday, 3, f)
    when 'k'; emit_a(hour, 2, f)
    when 'L'
      emit_n((sec_fraction / MILLISECONDS_IN_DAY).floor, 3, f)
    when 'l'; emit_a((hour % 12).nonzero? || 12, 2, f)
    when 'M', 'OM'; emit_n(min, 2, f)
    when 'm', 'Om'; emit_n(mon, 2, f)
    when 'N'
      emit_n((sec_fraction / NANOSECONDS_IN_DAY).floor, 9, f)
    when 'n'; "\n"
    when 'P'; emit_ad(strftime('%p').downcase, 0, f)
    when 'p'; emit_au(if hour < 12 then 'AM' else 'PM' end, 0, f)
    when 'Q'
      s = ((ajd - UNIX_EPOCH_IN_AJD) / MILLISECONDS_IN_DAY).round
      emit_sn(s, 1, f)
    when 'R'; emit_a(strftime('%H:%M'), 0, f)
    when 'r'; emit_a(strftime('%I:%M:%S %p'), 0, f)
    when 'S', 'OS'; emit_n(sec, 2, f)
    when 's'
      s = ((ajd - UNIX_EPOCH_IN_AJD) / SECONDS_IN_DAY).round
      emit_sn(s, 1, f)
    when 'T'
      if m == '%T'
        format('%02d:%02d:%02d', hour, min, sec) # 4p
      else
        emit_a(strftime('%H:%M:%S'), 0, f)
      end
    when 't'; "\t"
    when 'U', 'W', 'OU', 'OW'
      emit_n(if c[-1,1] == 'U' then wnum0 else wnum1 end, 2, f)
    when 'u', 'Ou'; emit_n(cwday, 1, f)
    when 'V', 'OV'; emit_n(cweek, 2, f)
    when 'v'; emit_a(strftime('%e-%b-%Y'), 0, f)
    when 'w', 'Ow'; emit_n(wday, 1, f)
    when 'X', 'EX'; emit_a(strftime('%H:%M:%S'), 0, f)
    when 'x', 'Ex'; emit_a(strftime('%m/%d/%y'), 0, f)
    when 'Y', 'EY'; emit_sn(year, 4, f)
    when 'y', 'Ey', 'Oy'; emit_n(year % 100, 2, f)
    when 'Z'; emit_au(strftime('%:z'), 0, f)
    when /\A(:{0,3})z/
      t = $1.size
      sign = if offset < 0 then -1 else +1 end
      fr = offset.abs
      ss = fr.div(SECONDS_IN_DAY) # 4p
      hh, ss = ss.divmod(3600)
      mm, ss = ss.divmod(60)
      if t == 3
        if    ss.nonzero? then t =  2
        elsif mm.nonzero? then t =  1
        else                   t = -1
        end
      end
      case t
      when -1
        tail = []
        sep = ''
      when 0
        f[:w] -= 2 if f[:w]
        tail = ['%02d' % mm]
        sep = ''
      when 1
        f[:w] -= 3 if f[:w]
        tail = ['%02d' % mm]
        sep = ':'
      when 2
        f[:w] -= 6 if f[:w]
        tail = ['%02d' % mm, '%02d' % ss]
        sep = ':'
      end
      ([emit_z(sign * hh, 2, f)] + tail).join(sep)
    when '%'; emit_a('%', 0, f)
    when '+'; emit_a(strftime('%a %b %e %H:%M:%S %Z %Y'), 0, f)
    when '1'
      if $VERBOSE
        warn("warning: strftime: %1 is deprecated; forget this")
      end
      emit_n(jd, 1, f)
    when '2'
      if $VERBOSE
        warn("warning: strftime: %2 is deprecated; use '%Y-%j'")
      end
      emit_a(strftime('%Y-%j'), 0, f)
    when '3'
      if $VERBOSE
        warn("warning: strftime: %3 is deprecated; use '%F'")
      end
      emit_a(strftime('%F'), 0, f)
    else
      a
    end
  end
end
            

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus