| Class | Date |
| In: |
lib/date/format.rb
lib/date.rb lib/yaml/rubytypes.rb |
| Parent: | Object |
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, Date::civil() (aliased to Date::new()) with year, month, and day-of-month, or Date::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.
| MONTHS | = | { 'january' => 1, 'february' => 2, 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6, 'july' => 7, 'august' => 8, 'september'=> 9, 'october' =>10, 'november' =>11, 'december' =>12 | ||
| DAYS | = | { 'sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday'=> 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6 | ||
| ABBR_MONTHS | = | { 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4, 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8, 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12 | ||
| ABBR_DAYS | = | { 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6 | ||
| ZONES | = | { 'ut' => 0*3600, 'gmt' => 0*3600, 'est' => -5*3600, 'edt' => -4*3600, 'cst' => -6*3600, 'cdt' => -5*3600, 'mst' => -7*3600, 'mdt' => -6*3600, 'pst' => -8*3600, 'pdt' => -7*3600, 'a' => 1*3600, 'b' => 2*3600, 'c' => 3*3600, 'd' => 4*3600, 'e' => 5*3600, 'f' => 6*3600, 'g' => 7*3600, 'h' => 8*3600, 'i' => 9*3600, 'k' => 10*3600, 'l' => 11*3600, 'm' => 12*3600, 'n' => -1*3600, 'o' => -2*3600, 'p' => -3*3600, 'q' => -4*3600, 'r' => -5*3600, 's' => -6*3600, 't' => -7*3600, 'u' => -8*3600, 'v' => -9*3600, 'w' =>-10*3600, 'x' =>-11*3600, 'y' =>-12*3600, 'z' => 0*3600, 'utc' => 0*3600, 'wet' => 0*3600, 'bst' => 1*3600, 'wat' => -1*3600, 'at' => -2*3600, 'ast' => -4*3600, 'adt' => -3*3600, 'yst' => -9*3600, 'ydt' => -8*3600, 'hst' =>-10*3600, 'hdt' => -9*3600, 'cat' =>-10*3600, 'ahst'=>-10*3600, 'nt' =>-11*3600, 'idlw'=>-12*3600, 'cet' => 1*3600, 'met' => 1*3600, 'mewt'=> 1*3600, 'mest'=> 2*3600, 'mesz'=> 2*3600, 'swt' => 1*3600, 'sst' => 2*3600, 'fwt' => 1*3600, 'fst' => 2*3600, 'eet' => 2*3600, 'bt' => 3*3600, 'zp4' => 4*3600, 'zp5' => 5*3600, 'zp6' => 6*3600, 'wast'=> 7*3600, 'wadt'=> 8*3600, 'cct' => 8*3600, 'jst' => 9*3600, 'east'=> 10*3600, 'eadt'=> 11*3600, 'gst' => 10*3600, 'nzt' => 12*3600, 'nzst'=> 12*3600, 'nzdt'=> 13*3600, 'idle'=> 12*3600 | ||
| PARSE_MONTHPAT | = | ABBR_MONTHS.keys.join('|') | ||
| PARSE_DAYPAT | = | ABBR_DAYS. keys.join('|') | ||
| MONTHNAMES | = | [nil] + %w(January February March April May June July August September October November December) | 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). | |
| DAYNAMES | = | %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) | 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. | |
| ABBR_MONTHNAMES | = | [nil] + %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) | Abbreviated month names, in English. | |
| ABBR_DAYNAMES | = | %w(Sun Mon Tue Wed Thu Fri Sat) | Abbreviated day names, in English. | |
| ITALY | = | 2299161 | The Julian Day Number of the Day of Calendar Reform for Italy and the Catholic countries. | |
| ENGLAND | = | 2361222 | The Julian Day Number of the Day of Calendar Reform for England and her Colonies. | |
| JULIAN | = | false | A constant used to indicate that a Date should always use the Julian calendar. | |
| GREGORIAN | = | true | A constant used to indicate that a Date should always use the Gregorian calendar. |
| gregorian_leap? | -> | leap? |
| new | -> | new0 |
| valid_civil? | -> | valid_date? |
| civil | -> | new |
Load from Marshall format.
# File lib/date.rb, line 1032
1032: def self._load(str)
1033: a = Marshal.load(str)
1034: if a.size == 2
1035: ajd, sg = a
1036: of = 0
1037: ajd -= 1.to_r/2
1038: else
1039: ajd, of, sg = a
1040: end
1041: new0(ajd, of, sg)
1042: end
# File lib/date/format.rb, line 252
252: def self._parse(str, comp=false)
253: str = str.dup
254:
255: str.gsub!(/[^-+,.\/:0-9a-z]+/ino, ' ')
256:
257: # day
258: if str.sub!(/(#{PARSE_DAYPAT})\S*/ino, ' ')
259: wday = ABBR_DAYS[$1.downcase]
260: end
261:
262: # time
263: if str.sub!(
264: /(\d+):(\d+)
265: (?:
266: :(\d+)(?:[,.](\d*))?
267: )?
268: (?:
269: \s*
270: ([ap])(?:m\b|\.m\.)
271: )?
272: (?:
273: \s*
274: (
275: [a-z]+(?:\s+dst)?\b
276: |
277: [-+]\d+(?::?\d+)
278: )
279: )?
280: /inox,
281: ' ')
282: hour = $1.to_i
283: min = $2.to_i
284: sec = $3.to_i if $3
285: if $4
286: sec_fraction = $4.to_i.to_r / (10**$4.size)
287: end
288:
289: if $5
290: hour %= 12
291: if $5.downcase == 'p'
292: hour += 12
293: end
294: end
295:
296: if $6
297: zone = $6
298: end
299: end
300:
301: # eu
302: if str.sub!(
303: /(\d+)\S*
304: \s+
305: (#{PARSE_MONTHPAT})\S*
306: (?:
307: \s+
308: (-?\d+)
309: )?
310: /inox,
311: ' ')
312: mday = $1.to_i
313: mon = ABBR_MONTHS[$2.downcase]
314:
315: if $3
316: year = $3.to_i
317: if $3.size > 2
318: comp = false
319: end
320: end
321:
322: # us
323: elsif str.sub!(
324: /(#{PARSE_MONTHPAT})\S*
325: \s+
326: (\d+)\S*
327: (?:
328: \s+
329: (-?\d+)
330: )?
331: /inox,
332: ' ')
333: mon = ABBR_MONTHS[$1.downcase]
334: mday = $2.to_i
335:
336: if $3
337: year = $3.to_i
338: if $3.size > 2
339: comp = false
340: end
341: end
342:
343: # iso
344: elsif str.sub!(/([-+]?\d+)-(\d+)-(-?\d+)/no, ' ')
345: year = $1.to_i
346: mon = $2.to_i
347: mday = $3.to_i
348:
349: if $1.size > 2
350: comp = false
351: elsif $3.size > 2
352: comp = false
353: mday, mon, year = year, mon, mday
354: end
355:
356: # jis
357: elsif str.sub!(/([MTSH])(\d+)\.(\d+)\.(\d+)/ino, ' ')
358: e = { 'm'=>1867,
359: 't'=>1911,
360: 's'=>1925,
361: 'h'=>1988
362: }[$1.downcase]
363: year = $2.to_i + e
364: mon = $3.to_i
365: mday = $4.to_i
366:
367: # vms
368: elsif str.sub!(/(-?\d+)-(#{PARSE_MONTHPAT})[^-]*-(-?\d+)/ino, ' ')
369: mday = $1.to_i
370: mon = ABBR_MONTHS[$2.downcase]
371: year = $3.to_i
372:
373: if $1.size > 2
374: comp = false
375: year, mon, mday = mday, mon, year
376: elsif $3.size > 2
377: comp = false
378: end
379:
380: # sla
381: elsif str.sub!(%r|(-?\d+)/(\d+)(?:/(-?\d+))?|no, ' ')
382: mon = $1.to_i
383: mday = $2.to_i
384:
385: if $3
386: year = $3.to_i
387: if $3.size > 2
388: comp = false
389: end
390: end
391:
392: if $3 && $1.size > 2
393: comp = false
394: year, mon, mday = mon, mday, year
395: end
396:
397: # ddd
398: elsif str.sub!(
399: /([-+]?)(\d{4,14})
400: (?:
401: \s*
402: T?
403: \s*
404: (\d{2,6})(?:[,.](\d*))?
405: )?
406: (?:
407: \s*
408: (
409: Z
410: |
411: [-+]\d{2,4}
412: )
413: \b
414: )?
415: /inox,
416: ' ')
417: case $2.size
418: when 4
419: mon = $2[ 0, 2].to_i
420: mday = $2[ 2, 2].to_i
421: when 6
422: year = ($1 + $2[ 0, 2]).to_i
423: mon = $2[ 2, 2].to_i
424: mday = $2[ 4, 2].to_i
425: when 8, 10, 12, 14
426: year = ($1 + $2[ 0, 4]).to_i
427: mon = $2[ 4, 2].to_i
428: mday = $2[ 6, 2].to_i
429: hour = $2[ 8, 2].to_i if $2.size >= 10
430: min = $2[10, 2].to_i if $2.size >= 12
431: sec = $2[12, 2].to_i if $2.size >= 14
432: comp = false
433: end
434: if $3
435: case $3.size
436: when 2, 4, 6
437: hour = $3[ 0, 2].to_i
438: min = $3[ 2, 2].to_i if $3.size >= 4
439: sec = $3[ 4, 2].to_i if $3.size >= 6
440: end
441: end
442: if $4
443: sec_fraction = $4.to_i.to_r / (10**$4.size)
444: end
445: if $5
446: zone = $5
447: end
448: end
449:
450: if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/ino, ' ')
451: if year
452: year = -year + 1
453: end
454: end
455:
456: if comp and year
457: if year >= 0 and year <= 99
458: if year >= 69
459: year += 1900
460: else
461: year += 2000
462: end
463: end
464: end
465:
466: elem = {}
467: elem[:year] = year if year
468: elem[:mon] = mon if mon
469: elem[:mday] = mday if mday
470: elem[:hour] = hour if hour
471: elem[:min] = min if min
472: elem[:sec] = sec if sec
473: elem[:sec_fraction] = sec_fraction if sec_fraction
474: elem[:zone] = zone if zone
475: offset = zone_to_diff(zone) if zone
476: elem[:offset] = offset if offset
477: elem[:wday] = wday if wday
478: elem
479: end
# File lib/date/format.rb, line 244
244: def self._strptime(str, fmt='%F')
245: elem = {}
246: elem if __strptime(str.dup, fmt, elem)
247: end
Convert an Astronomical Julian Day Number to an Astronomical Modified Julian Day Number.
# File lib/date.rb, line 448
448: def self.ajd_to_amjd(ajd) ajd - 4800001.to_r/2 end
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 lib/date.rb, line 414
414: def self.ajd_to_jd(ajd, of=0) clfloor(ajd + of + 1.to_r/2) end
Convert an Astronomical Modified Julian Day Number to an Astronomical Julian Day Number.
# File lib/date.rb, line 444
444: def self.amjd_to_ajd(amjd) amjd + 4800001.to_r/2 end
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 lib/date.rb, line 590
590: def self.civil(y=-4712, m=1, d=1, sg=ITALY)
591: unless jd = valid_civil?(y, m, d, sg)
592: raise ArgumentError, 'invalid date'
593: end
594: new0(jd_to_ajd(jd, 0, 0), 0, sg)
595: end
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 lib/date.rb, line 295
295: def self.civil_to_jd(y, m, d, sg=GREGORIAN)
296: if m <= 2
297: y -= 1
298: m += 12
299: end
300: a = (y / 100.0).floor
301: b = 2 - a + (a / 4.0).floor
302: jd = (365.25 * (y + 4716)).floor +
303: (30.6001 * (m + 1)).floor +
304: d + b - 1524
305: if os?(jd, sg)
306: jd -= b
307: end
308: jd
309: end
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 lib/date.rb, line 640
640: def self.commercial(y=1582, w=41, d=5, sg=ITALY)
641: unless jd = valid_commercial?(y, w, d, sg)
642: raise ArgumentError, 'invalid date'
643: end
644: new0(jd_to_ajd(jd, 0, 0), 0, sg)
645: end
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 lib/date.rb, line 384
384: def self.commercial_to_jd(y, w, d, ns=GREGORIAN)
385: jd = civil_to_jd(y, 1, 4, ns)
386: (jd - (((jd - 1) + 1) % 7)) +
387: 7 * (w - 1) +
388: (d - 1)
389: end
Convert a fractional day fr to [hours, minutes, seconds, fraction_of_a_second]
# File lib/date.rb, line 429
429: def self.day_fraction_to_time(fr)
430: h, fr = clfloor(fr, 1.to_r/24)
431: min, fr = clfloor(fr, 1.to_r/1440)
432: s, fr = clfloor(fr, 1.to_r/86400)
433: return h, min, s, fr
434: end
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 lib/date.rb, line 425
425: def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - 1.to_r/2 end
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 lib/date.rb, line 317
317: def self.jd_to_civil(jd, sg=GREGORIAN)
318: if os?(jd, sg)
319: a = jd
320: else
321: x = ((jd - 1867216.25) / 36524.25).floor
322: a = jd + 1 + x - (x / 4.0).floor
323: end
324: b = a + 1524
325: c = ((b - 122.1) / 365.25).floor
326: d = (365.25 * c).floor
327: e = ((b - d) / 30.6001).floor
328: dom = b - d - (30.6001 * e).floor
329: if e <= 13
330: m = e - 1
331: y = c - 4716
332: else
333: m = e - 13
334: y = c - 4715
335: end
336: return y, m, dom
337: end
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 lib/date.rb, line 369
369: def self.jd_to_commercial(jd, sg=GREGORIAN)
370: ns = ns?(jd, sg)
371: a = jd_to_civil(jd - 3, ns)[0]
372: y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end
373: w = 1 + ((jd - commercial_to_jd(y, 1, 1, ns)) / 7).floor
374: d = (jd + 1) % 7
375: if d.zero? then d = 7 end
376: return y, w, d
377: end
Convert a Julian Day Number to the number of days since the adoption of the Gregorian Calendar (in Italy).
# File lib/date.rb, line 464
464: def self.jd_to_ld(jd) jd - 2299160 end
Convert a Julian Day Number to a Modified Julian Day Number.
# File lib/date.rb, line 456
456: def self.jd_to_mjd(jd) jd - 2400001 end
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 lib/date.rb, line 356
356: def self.jd_to_ordinal(jd, sg=GREGORIAN)
357: y = jd_to_civil(jd, sg)[0]
358: doy = jd - civil_to_jd(y - 1, 12, 31, ns?(jd, sg))
359: return y, doy
360: end
Convert a count of the number of days since the adoption of the Gregorian Calendar (in Italy) to a Julian Day Number.
# File lib/date.rb, line 460
460: def self.ld_to_jd(ld) ld + 2299160 end
Convert a Modified Julian Day Number to a Julian Day Number.
# File lib/date.rb, line 452
452: def self.mjd_to_jd(mjd) mjd + 2400001 end
NOTE this is the documentation for the method new0(). 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.
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 Date::civil is generally easier and safer.
# File lib/date.rb, line 751
751: def initialize(ajd=0, of=0, sg=ITALY) @ajd, @of, @sg = ajd, of, sg end
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 lib/date.rb, line 538
538: def self.ordinal(y=-4712, d=1, sg=ITALY)
539: unless jd = valid_ordinal?(y, d, sg)
540: raise ArgumentError, 'invalid date'
541: end
542: new0(jd_to_ajd(jd, 0, 0), 0, sg)
543: end
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 lib/date.rb, line 276
276: def self.os? (jd, sg)
277: case sg
278: when Numeric; jd < sg
279: else; not sg
280: end
281: end
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 lib/date.rb, line 694
694: def self.parse(str='-4712-01-01', comp=false, sg=ITALY)
695: elem = _parse(str, comp)
696: new_with_hash(elem, sg)
697: end
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 lib/date.rb, line 674
674: def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY)
675: elem = _strptime(str, fmt)
676: new_with_hash(elem, sg)
677: end
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 lib/date.rb, line 557
557: def self.valid_civil? (y, m, d, sg=ITALY)
558: if m < 0
559: m += 13
560: end
561: if d < 0
562: ny, nm = clfloor(y * 12 + m, 12)
563: nm, = clfloor(nm + 1, 1)
564: jd = civil_to_jd(ny, nm, d + 1, sg)
565: ns = ns?(jd, sg)
566: return unless [y, m] == jd_to_civil(jd, sg)[0..1]
567: return unless [ny, nm, 1] == jd_to_civil(jd - d, ns)
568: else
569: jd = civil_to_jd(y, m, d, sg)
570: return unless [y, m, d] == jd_to_civil(jd, sg)
571: end
572: jd
573: end
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 lib/date.rb, line 613
613: def self.valid_commercial? (y, w, d, sg=ITALY)
614: if d < 0
615: d += 8
616: end
617: if w < 0
618: w = jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)[1]
619: end
620: jd = commercial_to_jd(y, w, d)
621: return unless ns?(jd, sg)
622: return unless [y, w, d] == jd_to_commercial(jd)
623: jd
624: end
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 lib/date.rb, line 514
514: def self.valid_ordinal? (y, d, sg=ITALY)
515: if d < 0
516: ny, = clfloor(y + 1, 1)
517: jd = ordinal_to_jd(ny, d + 1, sg)
518: ns = ns?(jd, sg)
519: return unless [y] == jd_to_ordinal(jd, sg)[0..0]
520: return unless [ny, 1] == jd_to_ordinal(jd - d, ns)
521: else
522: jd = ordinal_to_jd(y, d, sg)
523: return unless [y, d] == jd_to_ordinal(jd, sg)
524: end
525: jd
526: end
# File lib/date/format.rb, line 481
481: def self.zone_to_diff(str)
482: abb, dst = str.downcase.split(/\s+/o, 2)
483: if ZONES.include?(abb)
484: offset = ZONES[abb]
485: offset += 3600 if dst
486: elsif /\A([-+])(\d{2}):?(\d{2})?\Z/no =~ str
487: offset = $2.to_i * 3600 + $3.to_i * 60
488: offset *= -1 if $1 == '-'
489: end
490: offset
491: end
# File lib/date/format.rb, line 53
53: def self.__strptime(str, fmt, elem)
54: fmt.scan(/%[EO]?.|./mo) do |c|
55: cc = c.sub(/\A%[EO]?(.)\z/mo, '%\\1')
56: case cc
57: when /\A\s/o
58: str.sub!(/\A[\s\v]+/o, '')
59: when '%A', '%a'
60: return unless str.sub!(/\A([a-z]+)\b/io, '')
61: val = DAYS[$1.downcase] || ABBR_DAYS[$1.downcase]
62: return unless val
63: elem[:wday] = val
64: when '%B', '%b', '%h'
65: return unless str.sub!(/\A([a-z]+)\b/io, '')
66: val = MONTHS[$1.downcase] || ABBR_MONTHS[$1.downcase]
67: return unless val
68: elem[:mon] = val
69: when '%C'
70: return unless str.sub!(/\A(\d+)/o, '')
71: val = $1.to_i
72: elem[:cent] = val
73: when '%c'
74: return unless __strptime(str, '%a %b %e %H:%M:%S %Y', elem)
75: when '%D'
76: return unless __strptime(str, '%m/%d/%y', elem)
77: when '%d', '%e'
78: return unless str.sub!(/\A ?(\d+)/o, '')
79: val = $1.to_i
80: return unless (1..31) === val
81: elem[:mday] = val
82: when '%F'
83: return unless __strptime(str, '%Y-%m-%d', elem)
84: when '%G'
85: return unless str.sub!(/\A([-+]?\d+)/o, '')
86: val = $1.to_i
87: elem[:cwyear] = val
88: when '%g'
89: return unless str.sub!(/\A(\d+)/o, '')
90: val = $1.to_i
91: return unless (0..99) === val
92: elem[:cwyear] = val
93: elem[:cent] ||= if val >= 69 then 19 else 20 end
94: when '%H', '%k'
95: return unless str.sub!(/\A ?(\d+)/o, '')
96: val = $1.to_i
97: return unless (0..24) === val
98: elem[:hour] = val
99: when '%I', '%l'
100: return unless str.sub!(/\A ?(\d+)/o, '')
101: val = $1.to_i
102: return unless (1..12) === val
103: elem[:hour] = val
104: when '%j'
105: return unless str.sub!(/\A(\d+)/o, '')
106: val = $1.to_i
107: return unless (1..366) === val
108: elem[:yday] = val
109: when '%M'
110: return unless str.sub!(/\A(\d+)/o, '')
111: val = $1.to_i
112: return unless (0..59) === val
113: elem[:min] = val
114: when '%m'
115: return unless str.sub!(/\A(\d+)/o, '')
116: val = $1.to_i
117: return unless (1..12) === val
118: elem[:mon] = val
119: ??
120: when '%n'
121: return unless __strptime(str, ' ', elem)
122: when '%p', '%P'
123: return unless str.sub!(/\A([ap])(?:m\b|\.m\.)/io, '')
124: elem[:merid] = if $1.downcase == 'a' then 0 else 12 end
125: when '%R'
126: return unless __strptime(str, '%H:%M', elem)
127: when '%r'
128: return unless __strptime(str, '%I:%M:%S %p', elem)
129: when '%S'
130: return unless str.sub!(/\A(\d+)/o, '')
131: val = $1.to_i
132: return unless (0..60) === val
133: elem[:sec] = val
134: when '%s'
135: return unless str.sub!(/\A(\d+)/o, '')
136: val = $1.to_i
137: elem[:seconds] = val
138: when '%T'
139: return unless __strptime(str, '%H:%M:%S', elem)
140: when '%t'
141: return unless __strptime(str, ' ', elem)
142: when '%U', '%W'
143: return unless str.sub!(/\A(\d+)/o, '')
144: val = $1.to_i
145: return unless (0..53) === val
146: elem[if c[-1,1] == 'U' then :wnum0 else :wnum1 end] = val
147: when '%u'
148: return unless str.sub!(/\A(\d+)/o, '')
149: val = $1.to_i
150: return unless (1..7) === val
151: elem[:cwday] = val
152: when '%V'
153: return unless str.sub!(/\A(\d+)/o, '')
154: val = $1.to_i
155: return unless (1..53) === val
156: elem[:cweek] = val
157: when '%v'
158: return unless __strptime(str, '%e-%b-%Y', elem)
159: when '%w'
160: return unless str.sub!(/\A(\d+)/o, '')
161: val = $1.to_i
162: return unless (0..6) === val
163: elem[:wday] = val
164: when '%X'
165: return unless __strptime(str, '%H:%M:%S', elem)
166: when '%x'
167: return unless __strptime(str, '%m/%d/%y', elem)
168: when '%Y'
169: return unless str.sub!(/\A([-+]?\d+)/o, '')
170: val = $1.to_i
171: elem[:year] = val
172: when '%y'
173: return unless str.sub!(/\A(\d+)/o, '')
174: val = $1.to_i
175: return unless (0..99) === val
176: elem[:year] = val
177: elem[:cent] ||= if val >= 69 then 19 else 20 end
178: when '%Z', '%z'
179: return unless str.sub!(/\A([-+:a-z0-9]+(?:\s+dst\b)?)/io, '')
180: val = $1
181: elem[:zone] = val
182: offset = zone_to_diff(val)
183: elem[:offset] = offset
184: when '%%'
185: return unless str.sub!(/\A%/o, '')
186: when '%+'
187: return unless __strptime(str, '%a %b %e %H:%M:%S %Z %Y', elem)
188: ??
189: when '%1'
190: if $VERBOSE
191: warn("warning: %1 is deprecated; forget this")
192: end
193: return unless str.sub!(/\A(\d+)/o, '')
194: val = $1.to_i
195: elem[:jd] = val
196: when '%2'
197: if $VERBOSE
198: warn("warning: %2 is deprecated; use '%Y-%j'")
199: end
200: return unless __strptime(str, '%Y-%j', elem)
201: when '%3'
202: if $VERBOSE
203: warn("warning: %3 is deprecated; use '%F'")
204: end
205: return unless __strptime(str, '%F', elem)
206: when /\A%(.)/m
207: return unless str.sub!(Regexp.new('\\A' + Regexp.quote($1)), '')
208: else
209: return unless str.sub!(Regexp.new('\\A' + Regexp.quote(c)), '')
210: end
211: end
212:
213: if cent = elem.delete(:cent)
214: if elem[:cwyear]
215: elem[:cwyear] += cent * 100
216: end
217: if elem[:year]
218: elem[:year] += cent * 100
219: end
220: end
221:
222: if merid = elem.delete(:merid)
223: if elem[:hour]
224: elem[:hour] %= 12
225: elem[:hour] += merid
226: end
227: end
228:
229: str
230: end
# File lib/date.rb, line 647
647: def self.new_with_hash(elem, sg)
648: elem ||= {}
649: y, m, d = elem.values_at(:year, :mon, :mday)
650: if [y, m, d].include? nil
651: raise ArgumentError, '3 elements of civil date are necessary'
652: else
653: civil(y, m, d, sg)
654: end
655: end
Return a new Date object that is n days later than the current one.
n may be a negative value, in which case the new Date is earlier than the current one; however, #-() might be more intuitive.
If n is not a Numeric, a TypeError will be thrown. In particular, two Dates cannot be added to each other.
# File lib/date.rb, line 901
901: def + (n)
902: case n
903: when Numeric; return self.class.new0(@ajd + n, @of, @sg)
904: end
905: raise TypeError, 'expected numeric'
906: end
If x is a Numeric value, create a new Date object that is x days earlier than the current one.
If x is a Date, return the number of days between the two dates; or, more precisely, how many days later the current date is than x.
If x is neither Numeric nor a Date, a TypeError is raised.
# File lib/date.rb, line 916
916: def - (x)
917: case x
918: when Numeric; return self.class.new0(@ajd - x, @of, @sg)
919: when Date; return @ajd - x.ajd
920: end
921: raise TypeError, 'expected numeric or date'
922: end
Return a new Date object that is n months earlier than the current one.
If the day-of-the-month of the current Date is greater than the last day of the target month, the day-of-the-month of the returned Date will be the last day of the target month.
# File lib/date.rb, line 977
977: def << (n) self >> -n end
Compare this date with another date.
other can also be a Numeric value, in which case it is interpreted as an Astronomical Julian Day Number.
Comparison is by Astronomical Julian Day Number, including fractional days. This means that both the time and the timezone offset are taken into account when comparing two DateTime instances. When comparing a DateTime instance with a Date instance, the time of the latter will be considered as falling on midnight UTC.
# File lib/date.rb, line 935
935: def <=> (other)
936: case other
937: when Numeric; return @ajd <=> other
938: when Date; return @ajd <=> other.ajd
939: end
940: nil
941: end
The relationship operator for Date.
Compares dates by Julian Day Number. When comparing two DateTime instances, or a DateTime with a Date, the instances will be regarded as equivalent if they fall on the same date in local time.
# File lib/date.rb, line 949
949: def === (other)
950: case other
951: when Numeric; return jd == other
952: when Date; return jd == other.jd
953: end
954: false
955: end
Return a new Date object that is n months later than the current one.
If the day-of-the-month of the current Date is greater than the last day of the target month, the day-of-the-month of the returned Date will be the last day of the target month.
# File lib/date.rb, line 963
963: def >> (n)
964: y, m = clfloor(year * 12 + (mon - 1) + n, 12)
965: m, = clfloor(m + 1, 1)
966: d = mday
967: d -= 1 until jd2 = self.class.valid_civil?(y, m, d, ns?)
968: self + (jd2 - jd)
969: end
Get the date as an Astronomical Julian Day Number.
# File lib/date.rb, line 754
754: def ajd() @ajd end
Get the date as an Astronomical Modified Julian Day Number.
# File lib/date.rb, line 757
757: def amjd() self.class.ajd_to_amjd(@ajd) end
Get the commercial day of the week of this date. Monday is commercial day-of-week 1; Sunday is commercial day-of-week 7.
# File lib/date.rb, line 841
841: def cwday() commercial[2] end
Get the commercial week of the year of this date.
# File lib/date.rb, line 837
837: def cweek() commercial[1] end
Get the commercial year of this date. See Commercial Date in the introduction for how this differs from the normal year.
# File lib/date.rb, line 834
834: def cwyear() commercial[0] end
Return internal object state as a programmer-readable string.
# File lib/date.rb, line 1019
1019: def inspect() format('#<%s: %s,%s,%s>', self.class, @ajd, @of, @sg) end
Get the date as a Julian Day Number.
# File lib/date.rb, line 762
762: def jd() self.class.ajd_to_jd(@ajd, @of)[0] end
Get the date as the number of days since the Day of Calendar Reform (in Italy and the Catholic countries).
# File lib/date.rb, line 772
772: def ld() self.class.jd_to_ld(jd) end
Is this a leap year?
# File lib/date.rb, line 858
858: def leap?
859: self.class.jd_to_civil(self.class.civil_to_jd(year, 3, 1, ns?) - 1,
860: ns?)[-1] == 29
861: end
Get the date as a Modified Julian Day Number.
# File lib/date.rb, line 768
768: def mjd() self.class.jd_to_mjd(jd) end
Is the current date old-style (Julian Calendar)?
# File lib/date.rb, line 850
850: def os? () self.class.os?(jd, @sg) end
Step the current date forward step days at a time (or backward, if step is negative) until we reach limit (inclusive), yielding the resultant date at each step.
# File lib/date.rb, line 983
983: def step(limit, step) # :yield: date
984: da = self
985: op = [:-,:<=,:>=][step<=>0]
986: while da.__send__(op, limit)
987: yield da
988: da += step
989: end
990: self
991: end
# File lib/date/format.rb, line 493
493: def strftime(fmt='%F')
494: o = ''
495: fmt.scan(/%[EO]?.|./mo) do |c|
496: cc = c.sub(/\A%[EO]?(.)\z/mo, '%\\1')
497: case cc
498: when '%A'; o << DAYNAMES[wday]
499: when '%a'; o << ABBR_DAYNAMES[wday]
500: when '%B'; o << MONTHNAMES[mon]
501: when '%b'; o << ABBR_MONTHNAMES[mon]
502: when '%C'; o << '%02d' % (year / 100.0).floor # P2,ID
503: when '%c'; o << strftime('%a %b %e %H:%M:%S %Y')
504: when '%D'; o << strftime('%m/%d/%y') # P2,ID
505: when '%d'; o << '%02d' % mday
506: when '%e'; o << '%2d' % mday
507: when '%F'; o << strftime('%Y-%m-%d') # ID
508: when '%G'; o << '%.4d' % cwyear # ID
509: when '%g'; o << '%02d' % (cwyear % 100) # ID
510: when '%H'; o << '%02d' % hour
511: when '%h'; o << strftime('%b') # P2,ID
512: when '%I'; o << '%02d' % ((hour % 12).nonzero? or 12)
513: when '%j'; o << '%03d' % yday
514: when '%k'; o << '%2d' % hour # AR,TZ,GL
515: when '%l'; o << '%2d' % ((hour % 12).nonzero? or 12) # AR,TZ,GL
516: when '%M'; o << '%02d' % min
517: when '%m'; o << '%02d' % mon
518: ??
519: when '%n'; o << "\n" # P2,ID
520: when '%P'; o << if hour < 12 then 'am' else 'pm' end # GL
521: when '%p'; o << if hour < 12 then 'AM' else 'PM' end
522: when '%R'; o << strftime('%H:%M') # ID
523: when '%r'; o << strftime('%I:%M:%S %p') # P2,ID
524: when '%S'; o << '%02d' % sec
525: when '%s' # TZ,GL
526: d = ajd - self.class.jd_to_ajd(self.class.civil_to_jd(1970,1,1), 0)
527: s = (d * 86400).to_i
528: o << '%d' % s
529: when '%T'; o << strftime('%H:%M:%S') # P2,ID
530: when '%t'; o << "\t" # P2,ID
531: when '%U', '%W'
532: a = self.class.civil_to_jd(year, 1, 1, ns?) + 6
533: k = if c[-1,1] == 'U' then 0 else 1 end
534: w = (jd - (a - ((a - k) + 1) % 7) + 7) / 7
535: o << '%02d' % w
536: when '%u'; o << '%d' % cwday # P2,ID
537: when '%V'; o << '%02d' % cweek # P2,ID
538: when '%v'; o << strftime('%e-%b-%Y') # AR,TZ
539: when '%w'; o << '%d' % wday
540: when '%X'; o << strftime('%H:%M:%S')
541: when '%x'; o << strftime('%m/%d/%y')
542: when '%Y'; o << '%.4d' % year
543: when '%y'; o << '%02d' % (year % 100)
544: when '%Z'; o << (if offset.zero? then 'Z' else strftime('%z') end)
545: when '%z' # ID
546: o << if offset < 0 then '-' else '+' end
547: of = offset.abs
548: hh, fr = of.divmod(1.to_r/24)
549: mm = fr / (1.to_r/1440)
550: o << '%02d' % hh
551: o << '%02d' % mm
552: when '%%'; o << '%'
553: when '%+'; o << strftime('%a %b %e %H:%M:%S %Z %Y') # TZ
554: ??
555: when '%1'
556: if $VERBOSE
557: warn("warning: %1 is deprecated; forget this")
558: end
559: o << '%d' % jd
560: when '%2'
561: if $VERBOSE
562: warn("warning: %2 is deprecated; use '%Y-%j'")
563: end
564: o << strftime('%Y-%j')
565: when '%3'
566: if $VERBOSE
567: warn("warning: %3 is deprecated; use '%F'")
568: end
569: o << strftime('%F')
570: when /\A%(.)/m
571: o << $1
572: else
573: o << c
574: end
575: end
576: o
577: end
Return the date as a human-readable string.
The format used is YYYY-MM-DD.
# File lib/date.rb, line 1024
1024: def to_s() strftime end
# File lib/yaml/rubytypes.rb, line 349
349: def to_yaml( opts = {} )
350: YAML::quick_emit( object_id, opts ) do |out|
351: out.scalar( "tag:yaml.org,2002:timestamp", self.to_s, :plain )
352: end
353: end
Get the fraction-of-a-second of this date.
# File lib/date.rb, line 824
824: def sec_fraction() time[3] end