forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.rb
1832 lines (1595 loc) · 54.4 KB
/
date.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# date.rb - date and time library
#
# Author: Tadayoshi Funaba 1998-2008
#
# Documentation: William Webber <william@williamwebber.com>
#
#--
# $Id: date.rb,v 2.37 2008-01-17 20:16:31+09 tadf Exp $
#++
#
# == Overview
#
# This file provides two classes for working with
# dates and times.
#
# The first class, Date, represents dates.
# It works with years, months, weeks, and days.
# See the Date class documentation for more details.
#
# The second, DateTime, extends Date to include hours,
# minutes, seconds, and fractions of a second. It
# provides basic support for time zones. See the
# DateTime class documentation for more details.
#
# === Ways of calculating the date.
#
# In common usage, the date is reckoned in years since or
# before the Common Era (CE/BCE, also known as AD/BC), then
# as a month and day-of-the-month within the current year.
# This is known as the *Civil* *Date*, and abbreviated
# as +civil+ in the Date class.
#
# Instead of year, month-of-the-year, and day-of-the-month,
# the date can also be reckoned in terms of year and
# day-of-the-year. This is known as the *Ordinal* *Date*,
# and is abbreviated as +ordinal+ in the Date class. (Note
# that referring to this as the Julian date is incorrect.)
#
# The date can also be reckoned in terms of year, week-of-the-year,
# and day-of-the-week. This is known as the *Commercial*
# *Date*, and is abbreviated as +commercial+ in the
# Date class. The commercial week runs Monday (day-of-the-week
# 1) to Sunday (day-of-the-week 7), in contrast to the civil
# week which runs Sunday (day-of-the-week 0) to Saturday
# (day-of-the-week 6). The first week of the commercial year
# starts on the Monday on or before January 1, and the commercial
# year itself starts on this Monday, not January 1.
#
# For scientific purposes, it is convenient to refer to a date
# simply as a day count, counting from an arbitrary initial
# day. The date first chosen for this was January 1, 4713 BCE.
# A count of days from this date is the *Julian* *Day* *Number*
# or *Julian* *Date*, which is abbreviated as +jd+ in the
# Date class. This is in local time, and counts from midnight
# on the initial day. The stricter usage is in UTC, and counts
# from midday on the initial day. This is referred to in the
# Date class as the *Astronomical* *Julian* *Day* *Number*, and
# abbreviated as +ajd+. In the Date class, the Astronomical
# Julian Day Number includes fractional days.
#
# Another absolute day count is the *Modified* *Julian* *Day*
# *Number*, which takes November 17, 1858 as its initial day.
# This is abbreviated as +mjd+ in the Date class. There
# is also an *Astronomical* *Modified* *Julian* *Day* *Number*,
# which is in UTC and includes fractional days. This is
# abbreviated as +amjd+ in the Date class. Like the Modified
# Julian Day Number (and unlike the Astronomical Julian
# Day Number), it counts from midnight.
#
# Alternative calendars such as the Chinese Lunar Calendar,
# the Islamic Calendar, or the French Revolutionary Calendar
# are not supported by the Date class; nor are calendars that
# are based on an Era different from the Common Era, such as
# the Japanese Imperial Calendar or the Republic of China
# Calendar.
#
# === Calendar Reform
#
# The standard civil year is 365 days long. However, the
# solar year is fractionally longer than this. To account
# for this, a *leap* *year* is occasionally inserted. This
# is a year with 366 days, the extra day falling on February 29.
# In the early days of the civil calendar, every fourth
# year without exception was a leap year. This way of
# reckoning leap years is the *Julian* *Calendar*.
#
# However, the solar year is marginally shorter than 365 1/4
# days, and so the *Julian* *Calendar* gradually ran slow
# over the centuries. To correct this, every 100th year
# (but not every 400th year) was excluded as a leap year.
# This way of reckoning leap years, which we use today, is
# the *Gregorian* *Calendar*.
#
# The Gregorian Calendar was introduced at different times
# in different regions. The day on which it was introduced
# for a particular region is the *Day* *of* *Calendar*
# *Reform* for that region. This is abbreviated as +sg+
# (for Start of Gregorian calendar) in the Date class.
#
# Two such days are of particular
# significance. The first is October 15, 1582, which was
# the Day of Calendar Reform for Italy and most Catholic
# countries. The second is September 14, 1752, which was
# the Day of Calendar Reform for England and its colonies
# (including what is now the United States). These two
# dates are available as the constants Date::ITALY and
# Date::ENGLAND, respectively. (By comparison, Germany and
# Holland, less Catholic than Italy but less stubborn than
# England, changed over in 1698; Sweden in 1753; Russia not
# till 1918, after the Revolution; and Greece in 1923. Many
# Orthodox churches still use the Julian Calendar. A complete
# list of Days of Calendar Reform can be found at
# http://www.polysyllabic.com/GregConv.html.)
#
# Switching from the Julian to the Gregorian calendar
# involved skipping a number of days to make up for the
# accumulated lag, and the later the switch was (or is)
# done, the more days need to be skipped. So in 1582 in Italy,
# 4th October was followed by 15th October, skipping 10 days; in 1752
# in England, 2nd September was followed by 14th September, skipping
# 11 days; and if I decided to switch from Julian to Gregorian
# Calendar this midnight, I would go from 27th July 2003 (Julian)
# today to 10th August 2003 (Gregorian) tomorrow, skipping
# 13 days. The Date class is aware of this gap, and a supposed
# date that would fall in the middle of it is regarded as invalid.
#
# The Day of Calendar Reform is relevant to all date representations
# involving years. It is not relevant to the Julian Day Numbers,
# except for converting between them and year-based representations.
#
# In the Date and DateTime classes, the Day of Calendar Reform or
# +sg+ can be specified a number of ways. First, it can be as
# the Julian Day Number of the Day of Calendar Reform. Second,
# it can be using the constants Date::ITALY or Date::ENGLAND; these
# are in fact the Julian Day Numbers of the Day of Calendar Reform
# of the respective regions. Third, it can be as the constant
# Date::JULIAN, which means to always use the Julian Calendar.
# Finally, it can be as the constant Date::GREGORIAN, which means
# to always use the Gregorian Calendar.
#
# Note: in the Julian Calendar, New Years Day was March 25. The
# Date class does not follow this convention.
#
# === Time Zones
#
# DateTime objects support a simple representation
# of time zones. Time zones are represented as an offset
# from UTC, as a fraction of a day. This offset is the
# how much local time is later (or earlier) than UTC.
# UTC offset 0 is centred on England (also known as GMT).
# As you travel east, the offset increases until you
# reach the dateline in the middle of the Pacific Ocean;
# as you travel west, the offset decreases. This offset
# is abbreviated as +of+ in the Date class.
#
# This simple representation of time zones does not take
# into account the common practice of Daylight Savings
# Time or Summer Time.
#
# Most DateTime methods return the date and the
# time in local time. The two exceptions are
# #ajd() and #amjd(), which return the date and time
# in UTC time, including fractional days.
#
# The Date class does not support time zone offsets, in that
# there is no way to create a Date object with a time zone.
# However, methods of the Date class when used by a
# DateTime instance will use the time zone offset of this
# instance.
#
# == Examples of use
#
# === Print out the date of every Sunday between two dates.
#
# def print_sundays(d1, d2)
# d1 +=1 while (d1.wday != 0)
# d1.step(d2, 7) do |date|
# puts "#{Date::MONTHNAMES[date.mon]} #{date.day}"
# end
# end
#
# print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23))
#
# === Calculate how many seconds to go till midnight on New Year's Day.
#
# def secs_to_new_year(now = DateTime::now())
# new_year = DateTime.new(now.year + 1, 1, 1)
# dif = new_year - now
# hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif)
# return hours * 60 * 60 + mins * 60 + secs
# end
#
# puts secs_to_new_year()
require 'date/format'
# 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.
class Date
include Comparable
# 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).
MONTHNAMES = [nil] + %w(January February March April May June July
August September October November December)
# 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.
DAYNAMES = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
# Abbreviated month names, in English.
ABBR_MONTHNAMES = [nil] + %w(Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec)
# Abbreviated day names, in English.
ABBR_DAYNAMES = %w(Sun Mon Tue Wed Thu Fri Sat)
[MONTHNAMES, DAYNAMES, ABBR_MONTHNAMES, ABBR_DAYNAMES].each do |xs|
xs.each{|x| x.freeze unless x.nil?}.freeze
end
class Infinity < Numeric # :nodoc:
include Comparable
def initialize(d=1) @d = d <=> 0 end
def d() @d end
protected :d
def zero? () false end
def finite? () false end
def infinite? () d.nonzero? end
def nan? () d.zero? end
def abs() self.class.new end
def -@ () self.class.new(-d) end
def +@ () self.class.new(+d) end
def <=> (other)
case other
when Infinity; return d <=> other.d
when Numeric; return d
else
begin
l, r = other.coerce(self)
return l <=> r
rescue NoMethodError
end
end
nil
end
def coerce(other)
case other
when Numeric; return -d, d
else
super
end
end
end
# The Julian Day Number of the Day of Calendar Reform for Italy
# and the Catholic countries.
ITALY = 2299161 # 1582-10-15
# The Julian Day Number of the Day of Calendar Reform for England
# and her Colonies.
ENGLAND = 2361222 # 1752-09-14
# A constant used to indicate that a Date should always use the
# Julian calendar.
JULIAN = Infinity.new
# A constant used to indicate that a Date should always use the
# Gregorian calendar.
GREGORIAN = -Infinity.new
HALF_DAYS_IN_DAY = Rational(1, 2) # :nodoc:
HOURS_IN_DAY = Rational(1, 24) # :nodoc:
MINUTES_IN_DAY = Rational(1, 1440) # :nodoc:
SECONDS_IN_DAY = Rational(1, 86400) # :nodoc:
MILLISECONDS_IN_DAY = Rational(1, 86400*10**3) # :nodoc:
NANOSECONDS_IN_DAY = Rational(1, 86400*10**9) # :nodoc:
MILLISECONDS_IN_SECOND = Rational(1, 10**3) # :nodoc:
NANOSECONDS_IN_SECOND = Rational(1, 10**9) # :nodoc:
MJD_EPOCH_IN_AJD = Rational(4800001, 2) # 1858-11-17 # :nodoc:
UNIX_EPOCH_IN_AJD = Rational(4881175, 2) # 1970-01-01 # :nodoc:
MJD_EPOCH_IN_CJD = 2400001 # :nodoc:
UNIX_EPOCH_IN_CJD = 2440588 # :nodoc:
LD_EPOCH_IN_CJD = 2299160 # :nodoc:
t = Module.new do
private
def find_fdoy(y, sg) # :nodoc:
j = nil
1.upto(31) do |d|
break if j = _valid_civil?(y, 1, d, sg)
end
j
end
def find_ldoy(y, sg) # :nodoc:
j = nil
31.downto(1) do |d|
break if j = _valid_civil?(y, 12, d, sg)
end
j
end
def find_fdom(y, m, sg) # :nodoc:
j = nil
1.upto(31) do |d|
break if j = _valid_civil?(y, m, d, sg)
end
j
end
def find_ldom(y, m, sg) # :nodoc:
j = nil
31.downto(1) do |d|
break if j = _valid_civil?(y, m, d, sg)
end
j
end
# 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.
def ordinal_to_jd(y, d, sg=GREGORIAN) # :nodoc:
find_fdoy(y, sg) + d - 1
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]
def jd_to_ordinal(jd, sg=GREGORIAN) # :nodoc:
y = jd_to_civil(jd, sg)[0]
j = find_fdoy(y, sg)
doy = jd - j + 1
return y, doy
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.
def civil_to_jd(y, m, d, sg=GREGORIAN) # :nodoc:
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 jd < sg
jd -= b
end
jd
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.
def jd_to_civil(jd, sg=GREGORIAN) # :nodoc:
if 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
# 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.
def commercial_to_jd(y, w, d, sg=GREGORIAN) # :nodoc:
j = find_fdoy(y, sg) + 3
(j - (((j - 1) + 1) % 7)) +
7 * (w - 1) +
(d - 1)
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]
def jd_to_commercial(jd, sg=GREGORIAN) # :nodoc:
a = jd_to_civil(jd - 3, sg)[0]
y = if jd >= commercial_to_jd(a + 1, 1, 1, sg) then a + 1 else a end
w = 1 + ((jd - commercial_to_jd(y, 1, 1, sg)) / 7).floor
d = (jd + 1) % 7
d = 7 if d == 0
return y, w, d
end
def weeknum_to_jd(y, w, d, f=0, sg=GREGORIAN) # :nodoc:
a = find_fdoy(y, sg) + 6
(a - ((a - f) + 1) % 7 - 7) + 7 * w + d
end
def jd_to_weeknum(jd, f=0, sg=GREGORIAN) # :nodoc:
y, m, d = jd_to_civil(jd, sg)
a = find_fdoy(y, sg) + 6
w, d = (jd - (a - ((a - f) + 1) % 7) + 7).divmod(7)
return y, w, d
end
def nth_kday_to_jd(y, m, n, k, sg=GREGORIAN) # :nodoc:
j = if n > 0
find_fdom(y, m, sg) - 1
else
find_ldom(y, m, sg) + 7
end
(j - (((j - k) + 1) % 7)) + 7 * n
end
def jd_to_nth_kday(jd, sg=GREGORIAN) # :nodoc:
y, m, d = jd_to_civil(jd, sg)
j = find_fdom(y, m, sg)
return y, m, ((jd - j) / 7).floor + 1, jd_to_wday(jd)
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.
def ajd_to_jd(ajd, of=0) (ajd + of + HALF_DAYS_IN_DAY).divmod(1) end # :nodoc:
# 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.
def jd_to_ajd(jd, fr, of=0) jd + fr - of - HALF_DAYS_IN_DAY end # :nodoc:
# Convert a fractional day +fr+ to [hours, minutes, seconds,
# fraction_of_a_second]
def day_fraction_to_time(fr) # :nodoc:
ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p
h, ss = ss.divmod(3600)
min, s = ss.divmod(60)
return h, min, s, fr * 86400
end
# Convert an +h+ hour, +min+ minutes, +s+ seconds period
# to a fractional day.
begin
Rational(Rational(1, 2), 2) # a challenge
def time_to_day_fraction(h, min, s)
Rational(h * 3600 + min * 60 + s, 86400) # 4p
end
rescue
def time_to_day_fraction(h, min, s)
if Integer === h && Integer === min && Integer === s
Rational(h * 3600 + min * 60 + s, 86400) # 4p
else
(h * 3600 + min * 60 + s).to_r/86400 # 4p
end
end
end
# Convert an Astronomical Modified Julian Day Number to an
# Astronomical Julian Day Number.
def amjd_to_ajd(amjd) amjd + MJD_EPOCH_IN_AJD end # :nodoc:
# Convert an Astronomical Julian Day Number to an
# Astronomical Modified Julian Day Number.
def ajd_to_amjd(ajd) ajd - MJD_EPOCH_IN_AJD end # :nodoc:
# Convert a Modified Julian Day Number to a Julian
# Day Number.
def mjd_to_jd(mjd) mjd + MJD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to a Modified Julian Day
# Number.
def jd_to_mjd(jd) jd - MJD_EPOCH_IN_CJD end # :nodoc:
# Convert a count of the number of days since the adoption
# of the Gregorian Calendar (in Italy) to a Julian Day Number.
def ld_to_jd(ld) ld + LD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to the number of days since
# the adoption of the Gregorian Calendar (in Italy).
def jd_to_ld(jd) jd - LD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to the day of the week.
#
# Sunday is day-of-week 0; Saturday is day-of-week 6.
def jd_to_wday(jd) (jd + 1) % 7 end # :nodoc:
# Is +jd+ a valid Julian Day Number?
#
# If it is, returns it. In fact, any value is treated as a valid
# Julian Day Number.
def _valid_jd? (jd, sg=GREGORIAN) jd end # :nodoc:
# 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.
def _valid_ordinal? (y, d, sg=GREGORIAN) # :nodoc:
if d < 0
j = find_ldoy(y, sg)
ny, nd = jd_to_ordinal(j + d + 1, sg)
return unless ny == y
d = nd
end
jd = ordinal_to_jd(y, d, sg)
return unless [y, d] == jd_to_ordinal(jd, sg)
jd
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.
def _valid_civil? (y, m, d, sg=GREGORIAN) # :nodoc:
if m < 0
m += 13
end
if d < 0
j = find_ldom(y, m, sg)
ny, nm, nd = jd_to_civil(j + d + 1, sg)
return unless [ny, nm] == [y, m]
d = nd
end
jd = civil_to_jd(y, m, d, sg)
return unless [y, m, d] == jd_to_civil(jd, sg)
jd
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.
def _valid_commercial? (y, w, d, sg=GREGORIAN) # :nodoc:
if d < 0
d += 8
end
if w < 0
ny, nw, nd =
jd_to_commercial(commercial_to_jd(y + 1, 1, 1, sg) + w * 7, sg)
return unless ny == y
w = nw
end
jd = commercial_to_jd(y, w, d, sg)
return unless [y, w, d] == jd_to_commercial(jd, sg)
jd
end
def _valid_weeknum? (y, w, d, f, sg=GREGORIAN) # :nodoc:
if d < 0
d += 7
end
if w < 0
ny, nw, nd, nf =
jd_to_weeknum(weeknum_to_jd(y + 1, 1, f, f, sg) + w * 7, f, sg)
return unless ny == y
w = nw
end
jd = weeknum_to_jd(y, w, d, f, sg)
return unless [y, w, d] == jd_to_weeknum(jd, f, sg)
jd
end
def _valid_nth_kday? (y, m, n, k, sg=GREGORIAN) # :nodoc:
if k < 0
k += 7
end
if n < 0
ny, nm = (y * 12 + m).divmod(12)
nm, = (nm + 1) .divmod(1)
ny, nm, nn, nk =
jd_to_nth_kday(nth_kday_to_jd(ny, nm, 1, k, sg) + n * 7, sg)
return unless [ny, nm] == [y, m]
n = nn
end
jd = nth_kday_to_jd(y, m, n, k, sg)
return unless [y, m, n, k] == jd_to_nth_kday(jd, sg)
jd
end
# 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.
def _valid_time? (h, min, s) # :nodoc:
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
end
extend t
include t
# Is a year a leap year in the Julian calendar?
#
# All years divisible by 4 are leap years in the Julian calendar.
def self.julian_leap? (y) y % 4 == 0 end
# 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.
def self.gregorian_leap? (y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0 end
class << self; alias_method :leap?, :gregorian_leap? end
class << self; alias_method :new!, :new end
def self.valid_jd? (jd, sg=ITALY)
!!_valid_jd?(jd, sg)
end
def self.valid_ordinal? (y, d, sg=ITALY)
!!_valid_ordinal?(y, d, sg)
end
def self.valid_civil? (y, m, d, sg=ITALY)
!!_valid_civil?(y, m, d, sg)
end
class << self; alias_method :valid_date?, :valid_civil? end
def self.valid_commercial? (y, w, d, sg=ITALY)
!!_valid_commercial?(y, w, d, sg)
end
def self.valid_weeknum? (y, w, d, f, sg=ITALY) # :nodoc:
!!_valid_weeknum?(y, w, d, f, sg)
end
private_class_method :valid_weeknum?
def self.valid_nth_kday? (y, m, n, k, sg=ITALY) # :nodoc:
!!_valid_nth_kday?(y, m, n, k, sg)
end
private_class_method :valid_nth_kday?
def self.valid_time? (h, min, s) # :nodoc:
!!_valid_time?(h, min, s)
end
private_class_method :valid_time?
# 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.
def self.jd(jd=0, sg=ITALY)
jd = _valid_jd?(jd, sg)
new!(jd_to_ajd(jd, 0, 0), 0, 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.
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
# 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.
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
class << self; alias_method :new, :civil 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 -4712, +w+ to 1, and +d+ to 1; this is
# Julian Day Number day 0.
#
# +sg+ specifies the Day of Calendar Reform.
def self.commercial(y=-4712, w=1, d=1, 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
def self.weeknum(y=-4712, w=0, d=1, f=0, sg=ITALY)
unless jd = _valid_weeknum?(y, w, d, f, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
private_class_method :weeknum
def self.nth_kday(y=-4712, m=1, n=1, k=1, sg=ITALY)
unless jd = _valid_nth_kday?(y, m, n, k, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
private_class_method :nth_kday
def self.rewrite_frags(elem) # :nodoc:
elem ||= {}
if seconds = elem[:seconds]
d, fr = seconds.divmod(86400)
h, fr = fr.divmod(3600)
min, fr = fr.divmod(60)
s, fr = fr.divmod(1)
elem[:jd] = UNIX_EPOCH_IN_CJD + d
elem[:hour] = h
elem[:min] = min
elem[:sec] = s
elem[:sec_fraction] = fr
elem.delete(:seconds)
elem.delete(:offset)
end
elem
end
private_class_method :rewrite_frags
def self.complete_frags(elem) # :nodoc:
i = 0
g = [[:time, [:hour, :min, :sec]],
[nil, [:jd]],
[:ordinal, [:year, :yday, :hour, :min, :sec]],
[:civil, [:year, :mon, :mday, :hour, :min, :sec]],
[:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec]],
[:wday, [:wday, :hour, :min, :sec]],
[:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec]],
[:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec]],
[nil, [:cwyear, :cweek, :wday, :hour, :min, :sec]],
[nil, [:year, :wnum0, :cwday, :hour, :min, :sec]],
[nil, [:year, :wnum1, :cwday, :hour, :min, :sec]]].
collect{|k, a| e = elem.values_at(*a).compact; [k, a, e]}.
select{|k, a, e| e.size > 0}.
sort_by{|k, a, e| [e.size, i -= 1]}.last
d = nil
if g && g[0] && (g[1].size - g[2].size) != 0
d ||= Date.today
case g[0]
when :ordinal
elem[:year] ||= d.year
elem[:yday] ||= 1
when :civil
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:mon] ||= 1
elem[:mday] ||= 1
when :commercial
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:cweek] ||= 1
elem[:cwday] ||= 1
when :wday
elem[:jd] ||= (d - d.wday + elem[:wday]).jd
when :wnum0
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:wnum0] ||= 0
elem[:wday] ||= 0
when :wnum1
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:wnum1] ||= 0
elem[:wday] ||= 0
end
end
if g && g[0] == :time
if self <= DateTime
d ||= Date.today
elem[:jd] ||= d.jd
end
end
elem[:hour] ||= 0
elem[:min] ||= 0
elem[:sec] ||= 0
elem[:sec] = [elem[:sec], 59].min
elem
end
private_class_method :complete_frags
def self.valid_date_frags?(elem, sg) # :nodoc:
catch :jd do
a = elem.values_at(:jd)
if a.all?
if jd = _valid_jd?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :yday)
if a.all?
if jd = _valid_ordinal?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :mon, :mday)
if a.all?
if jd = _valid_civil?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:cwyear, :cweek, :cwday)
if a[2].nil? && elem[:wday]
a[2] = elem[:wday].nonzero? || 7
end
if a.all?
if jd = _valid_commercial?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :wnum0, :wday)
if a[2].nil? && elem[:cwday]
a[2] = elem[:cwday] % 7
end
if a.all?
if jd = _valid_weeknum?(*(a << 0 << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :wnum1, :wday)
if a[2]
a[2] = (a[2] - 1) % 7
end
if a[2].nil? && elem[:cwday]
a[2] = (elem[:cwday] - 1) % 7
end