-
Notifications
You must be signed in to change notification settings - Fork 915
/
RubyDate.java
2531 lines (2131 loc) · 100 KB
/
RubyDate.java
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
/*
**** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2017-2018 The JRuby Team
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.date;
import org.jcodings.specific.USASCIIEncoding;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Chronology;
import org.joda.time.Instant;
import org.joda.time.chrono.GJChronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.JulianChronology;
import org.joni.Regex;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.java.proxies.JavaProxy;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.*;
import org.jruby.util.log.Logger;
import org.jruby.util.log.LoggerFactory;
import java.io.Serializable;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import static org.jruby.RubyRegexp.*;
import static org.jruby.ext.date.DateUtils.*;
import static org.jruby.util.Numeric.*;
/**
* JRuby's <code>Date</code> implementation - 'native' parts.
* In MRI, since 2.x, all of date.rb has been moved to native (C) code.
*
* NOTE: There's still date.rb, where this gets bootstrapped from.
*
* @since 9.2
*
* @author enebo
* @author kares
*/
@JRubyClass(name = "Date")
public class RubyDate extends RubyObject {
static final Logger LOG = LoggerFactory.getLogger(RubyDate.class);
static final GJChronology CHRONO_ITALY = GJChronology.getInstance();
static final GJChronology CHRONO_ITALY_UTC = GJChronology.getInstance(DateTimeZone.UTC);
// The Julian Day Number of the Day of Calendar Reform for Italy
// and the Catholic countries.
static final int ITALY = 2299161; // 1582-10-15
// The Julian Day Number of the Day of Calendar Reform for England
// and her Colonies.
static final int ENGLAND = 2361222; // 1752-09-14
// A constant used to indicate that a Date should always use the Julian calendar.
private static final double JULIAN_INFINITY = Double.POSITIVE_INFINITY; // Infinity.new
static final long JULIAN = (long) JULIAN_INFINITY; // Infinity.new
// A constant used to indicate that a Date should always use the Gregorian calendar.
private static final double GREGORIAN_INFINITY = Double.NEGATIVE_INFINITY; // -Infinity.new
static final long GREGORIAN = (long) GREGORIAN_INFINITY; // -Infinity.new
static final int REFORM_BEGIN_YEAR = 1582;
static final int REFORM_END_YEAR = 1930;
protected RubyDate(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
DateTime dt;
int off; // @of (in seconds)
long start = ITALY; // @sg
long subMillisNum = 0, subMillisDen = 1; // @sub_millis
static RubyClass createDateClass(Ruby runtime) {
RubyClass Date = runtime.defineClass("Date", runtime.getObject(), ALLOCATOR);
Date.setReifiedClass(RubyDate.class);
Date.includeModule(runtime.getComparable());
Date.defineAnnotatedMethods(RubyDate.class);
Date.setConstant("ITALY", runtime.newFixnum(ITALY));
Date.setConstant("ENGLAND", runtime.newFixnum(ENGLAND));
return Date;
}
// Julian Day Number day 0 ... `def self.civil(y=-4712, m=1, d=1, sg=ITALY)`
static final DateTime defaultDateTime = new DateTime(-4712 - 1, 1, 1, 0, 0, CHRONO_ITALY_UTC);
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyDate(runtime, klass, defaultDateTime);
}
};
static RubyClass getDate(final Ruby runtime) {
return (RubyClass) runtime.getObject().getConstantAt("Date");
}
static RubyClass getDateTime(final Ruby runtime) {
return (RubyClass) runtime.getObject().getConstantAt("DateTime");
}
public RubyDate(Ruby runtime, RubyClass klass, DateTime dt) {
super(runtime, klass);
this.dt = dt; // assuming of = 0 (UTC)
}
public RubyDate(Ruby runtime, DateTime dt) {
this(runtime, getDate(runtime), dt);
}
RubyDate(Ruby runtime, RubyClass klass, DateTime dt, int off, long start) {
super(runtime, klass);
this.dt = dt;
this.off = off; this.start = start;
}
RubyDate(Ruby runtime, RubyClass klass, DateTime dt, int off, long start, long subMillisNum, long subMillisDen) {
super(runtime, klass);
this.dt = dt;
this.off = off; this.start = start;
this.subMillisNum = subMillisNum; this.subMillisDen = subMillisDen;
}
public RubyDate(Ruby runtime, long millis, Chronology chronology) {
super(runtime, getDate(runtime));
this.dt = new DateTime(millis, chronology);
}
RubyDate(ThreadContext context, RubyClass klass, IRubyObject ajd, Chronology chronology, int off) {
this(context, klass, ajd, chronology, off, ITALY);
}
RubyDate(ThreadContext context, RubyClass klass, IRubyObject ajd, int off, long start) {
this(context, klass, ajd, getChronology(context, start, off), off, start);
}
RubyDate(ThreadContext context, RubyClass klass, IRubyObject ajd, long[] rest, int off, long start) {
this(context, klass, ajd, getChronology(context, start, off), off, start);
if (rest[0] != 0) adjustWithDayFraction(context, this.dt, rest);
}
private RubyDate(ThreadContext context, RubyClass klass, IRubyObject ajd, Chronology chronology, int off, long start) {
super(context.runtime, klass);
this.dt = new DateTime(initMillis(context, ajd), chronology);
this.off = off; this.start = start;
}
final RubyDate newInstance(final ThreadContext context, final DateTime dt, int off, long start) {
return newInstance(context, dt, off, start, subMillisNum, subMillisDen);
}
// to be overriden by RubyDateTime
RubyDate newInstance(final ThreadContext context, final DateTime dt, int off, long start, long subNum, long subDen) {
return new RubyDate(context.runtime, getMetaClass(), dt, off, start, subNum, subDen);
}
/**
* @note since <code>Date.new</code> is a <code>civil</code> alias, this won't ever get used
* @deprecated kept due AR-JDBC (uses RubyClass.newInstance(...) to 'fast' allocate a Date instance)
*/
@JRubyMethod(visibility = Visibility.PRIVATE)
public RubyDate initialize(ThreadContext context, IRubyObject dt) {
this.dt = (DateTime) JavaUtil.unwrapJavaValue(dt);
return this;
}
@JRubyMethod(visibility = Visibility.PRIVATE)
public RubyDate initialize(ThreadContext context, IRubyObject ajd, IRubyObject of) {
initialize(context, ajd, of, ITALY);
return this;
}
@JRubyMethod(visibility = Visibility.PRIVATE) // used by marshal_load
public RubyDate initialize(ThreadContext context, IRubyObject ajd, IRubyObject of, IRubyObject sg) {
initialize(context, ajd, of, val2sg(context, sg));
return this;
}
private void initialize(final ThreadContext context, IRubyObject arg, IRubyObject of, final long start) {
final int off = val2off(context, of);
this.off = off; this.start = start;
if (arg instanceof JavaProxy) { // backwards - compatibility with JRuby's date.rb
this.dt = (DateTime) JavaUtil.unwrapJavaValue(arg);
return;
}
this.dt = new DateTime(initMillis(context, arg), getChronology(context, start, off));
}
static final int DAY_IN_SECONDS = 86_400; // 24 * 60 * 60
static final int DAY_MS = 86_400_000; // 24 * 60 * 60 * 1000
private RubyFixnum DAY_MS_CACHE;
private long initMillis(final ThreadContext context, IRubyObject ajd) {
final Ruby runtime = context.runtime;
// cannot use DateTimeUtils.fromJulianDay since we need to keep ajd as a Rational for precision
// millis, @sub_millis = ((ajd - UNIX_EPOCH_IN_AJD) * 86400000).divmod(1)
IRubyObject val;
if (ajd instanceof RubyFixnum) {
val = ((RubyFixnum) ajd).op_minus(context, 4881175 / 2);
val = ((RubyFixnum) val).op_mul(context, DAY_MS);
val = ((RubyInteger) val).op_plus(context, RubyFixnum.newFixnum(runtime, DAY_MS / 2)); // missing 1/2
}
else {
RubyRational _UNIX_EPOCH_IN_AJD = RubyRational.newRational(runtime, -4881175, 2); // -(1970-01-01)
val = _UNIX_EPOCH_IN_AJD.op_plus(context, ajd);
val = DAY_MS(context).op_mul(context, val);
}
if (val instanceof RubyFixnum) {
return ((RubyFixnum) val).getLongValue();
}
// fallback
val = ((RubyNumeric) val).divmod(context, RubyFixnum.one(context.runtime));
IRubyObject millis = ((RubyArray) val).eltInternal(0);
if (!(millis instanceof RubyFixnum)) { // > java.lang.Long::MAX_VALUE
throw runtime.newArgumentError("Date out of range: millis=" + millis + " (" + millis.getMetaClass() + ")");
}
IRubyObject subMillis = ((RubyArray) val).eltInternal(1);
this.subMillisNum = ((RubyNumeric) subMillis).numerator(context).convertToInteger().getLongValue();
this.subMillisDen = ((RubyNumeric) subMillis).denominator(context).convertToInteger().getLongValue();
return ((RubyFixnum) millis).getLongValue();
}
private RubyFixnum DAY_MS(final ThreadContext context) {
RubyFixnum v = DAY_MS_CACHE;
if (v == null) v = DAY_MS_CACHE = context.runtime.newFixnum(DAY_MS);
return v;
}
@Override
public IRubyObject initialize_copy(IRubyObject original) {
final RubyDate from = (RubyDate) original;
this.dt = from.dt; this.off = from.off; this.start = from.start;
this.subMillisNum = from.subMillisNum; this.subMillisDen = from.subMillisDen;
return this;
}
// Date.new!(dt_or_ajd=0, of=0, sg=ITALY, sub_millis=0)
/**
* @deprecated internal Date.new!
*/
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static RubyDate new_(ThreadContext context, IRubyObject self) {
if (self == getDateTime(context.runtime)) {
return new RubyDateTime(context.runtime, 0, CHRONO_ITALY_UTC);
}
return new RubyDate(context.runtime, 0, CHRONO_ITALY_UTC);
}
/**
* @deprecated internal Date.new!
*/
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd) {
if (ajd instanceof JavaProxy) { // backwards - compatibility with JRuby's date.rb
if (self == getDateTime(context.runtime)) {
return new RubyDateTime(context.runtime, (RubyClass) self, (DateTime) JavaUtil.unwrapJavaValue(ajd));
}
return new RubyDate(context.runtime, (RubyClass) self, (DateTime) JavaUtil.unwrapJavaValue(ajd));
}
if (self == getDateTime(context.runtime)) {
return new RubyDateTime(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0);
}
return new RubyDate(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0);
}
/**
* @deprecated internal Date.new!
*/
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd, IRubyObject of) {
if (self == getDateTime(context.runtime)) {
return new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of);
}
return new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of);
}
/**
* @deprecated internal Date.new!
*/
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd, IRubyObject of, IRubyObject sg) {
if (self == getDateTime(context.runtime)) {
return new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg);
}
return new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg);
}
/**
# 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.
**/
// Date.civil([year=-4712[, month=1[, mday=1[, start=Date::ITALY]]]])
// Date.new([year=-4712[, month=1[, mday=1[, start=Date::ITALY]]]])
@JRubyMethod(name = "civil", alias = "new", meta = true)
public static RubyDate civil(ThreadContext context, IRubyObject self) {
return new RubyDate(context.runtime, (RubyClass) self, defaultDateTime);
}
@JRubyMethod(name = "civil", alias = "new", meta = true)
public static RubyDate civil(ThreadContext context, IRubyObject self, IRubyObject year) {
return new RubyDate(context.runtime, (RubyClass) self, civilImpl(context, year));
}
static DateTime civilImpl(ThreadContext context, IRubyObject year) {
int y = getYear(year);
final DateTime dt;
try {
dt = defaultDateTime.withYear(y);
}
catch (IllegalArgumentException ex) {
throw context.runtime.newArgumentError("invalid date");
}
return dt;
}
@JRubyMethod(name = "civil", alias = "new", meta = true)
public static RubyDate civil(ThreadContext context, IRubyObject self, IRubyObject year, IRubyObject month) {
return new RubyDate(context.runtime, (RubyClass) self, civilImpl(context, year, month));
}
static DateTime civilImpl(ThreadContext context, IRubyObject year, IRubyObject month) {
int y = getYear(year);
int m = getMonth(month);
final DateTime dt;
final Chronology chronology = defaultDateTime.getChronology();
long millis = defaultDateTime.getMillis();
try {
millis = chronology.year().set(millis, y);
millis = chronology.monthOfYear().set(millis, m);
dt = defaultDateTime.withMillis(millis);
}
catch (IllegalArgumentException ex) {
throw context.runtime.newArgumentError("invalid date");
}
return dt;
}
@JRubyMethod(name = "civil", alias = "new", meta = true)
public static RubyDate civil(ThreadContext context, IRubyObject self, IRubyObject year, IRubyObject month, IRubyObject mday) {
// return civil(context, self, new IRubyObject[] { year, month, mday, RubyFixnum.newFixnum(context.runtime, ITALY) });
return civilImpl(context, (RubyClass) self, year, month, mday, ITALY);
}
private static RubyDate civilImpl(ThreadContext context, RubyClass klass,
IRubyObject year, IRubyObject month, IRubyObject mday, final long sg) {
final int y = (sg > 0) ? getYear(year) : year.convertToInteger().getIntValue();
final int m = getMonth(month);
final long[] rest = new long[] { 0, 1 };
final int d = (int) RubyDateTime.getDay(context, mday, rest);
DateTime dt = civilDate(context, y, m ,d, getChronology(context, sg, 0));
RubyDate date = new RubyDate(context.runtime, klass, dt, 0, sg);
if (rest[0] != 0) date.adjustWithDayFraction(context, dt, rest);
return date;
}
@JRubyMethod(name = "civil", alias = "new", meta = true, optional = 4) // 4 args case
public static RubyDate civil(ThreadContext context, IRubyObject self, IRubyObject[] args) {
// IRubyObject year, IRubyObject month, IRubyObject mday, IRubyObject start
switch (args.length) {
// NOTE: slightly annoying but send might route its Date.send(:civil, *args) here
case 0: return civil(context, self);
case 1: return civil(context, self, args[0]);
case 2: return civil(context, self, args[0], args[1]);
// besides the above note on send ^^
// interpreter does not have a ThreeOperandArgNoBlockCallInstr thus routes 3 args as args[] here
case 3: return civil(context, self, args[0], args[1], args[2]);
}
final long sg = val2sg(context, args[3]);
return civilImpl(context, (RubyClass) self, args[0], args[1], args[2], sg);
}
static DateTime civilDate(ThreadContext context, final int y, final int m, final int d, final Chronology chronology) {
DateTime dt;
try {
if (d >= 0) { // let d == 0 fail (raise 'invalid date')
dt = new DateTime(y, m, d, 0, 0, chronology);
}
else {
dt = new DateTime(y, m, 1, 0, 0, chronology);
long ms = dt.getMillis();
int last = chronology.dayOfMonth().getMaximumValue(ms);
ms = chronology.dayOfMonth().set(ms, last + d + 1); // d < 0 (d == -1 -> d == 31)
dt = dt.withMillis(ms);
}
}
catch (IllegalArgumentException ex) {
debug(context, "invalid date", ex);
throw context.runtime.newArgumentError("invalid date");
}
return dt;
}
// NOTE: no Bignum special care since JODA does not support 'huge' years anyway
static int getYear(IRubyObject year) {
int y = year.convertToInteger().getIntValue(); // handles Rational(x, y)
return (y <= 0) ? --y : y; // due julian date calc -> see adjustJodaYear
}
static int getMonth(IRubyObject month) {
int m = month.convertToInteger().getIntValue(); // handles Rational(x, y)
return (m < 0) ? m + 13 : m;
}
@JRubyMethod(name = "valid_civil?", alias = "valid_date?", meta = true, required = 3, optional = 1)
public static IRubyObject valid_civil_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 3 ? val2sg(context, args[3]) : ITALY;
final Long jd = validCivilImpl(args[0], args[1], args[2], sg);
return jd == null ? context.fals : context.tru;
}
static Long validCivilImpl(IRubyObject year, IRubyObject month, IRubyObject day, final long sg) {
final int y = year.convertToInteger().getIntValue();
final int m = getMonth(month);
final int d = day.convertToInteger().getIntValue();
return DateUtils._valid_civil_p(y, m, d, sg);
}
// 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.
@JRubyMethod(name = "_valid_time?", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_time_p(ThreadContext context, IRubyObject self,
IRubyObject h, IRubyObject m, IRubyObject s) {
long hour = normIntValue(h, 24);
long min = normIntValue(m, 60);
long sec = normIntValue(s, 60);
if (valid_time_p(hour, min, sec)) {
return timeToDayFraction(context, (int) hour, (int) min, (int) sec);
}
return context.nil;
}
private static long normIntValue(IRubyObject val, final int negOffset) {
long v;
if (val instanceof RubyFixnum) {
v = ((RubyFixnum) val).getLongValue();
}
else {
v = val.convertToInteger().getLongValue();
}
return (v < 0) ? v + negOffset : v;
}
// Rational(h * 3600 + min * 60 + s, 86400)
static RubyNumeric timeToDayFraction(ThreadContext context, int hour, int min, int sec) {
return (RubyNumeric) RubyRational.newRationalCanonicalize(context, hour * 3600 + min * 60 + sec, DAY_IN_SECONDS);
}
/**
* 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.
*/
@JRubyMethod(name = "jd", meta = true)
public static RubyDate jd(ThreadContext context, IRubyObject self) { // jd = 0, sg = ITALY
return new RubyDate(context.runtime, (RubyClass) self, defaultDateTime);
}
@JRubyMethod(name = "jd", meta = true)
public static RubyDate jd(ThreadContext context, IRubyObject self, IRubyObject jd) { // sg = ITALY
return jdImpl(context, self, jd, ITALY);
}
@JRubyMethod(name = "jd", meta = true)
public static RubyDate jd(ThreadContext context, IRubyObject self, IRubyObject jd, IRubyObject sg) {
return jdImpl(context, self, jd, val2sg(context, sg));
}
private static RubyDate jdImpl(ThreadContext context, IRubyObject self, IRubyObject jd, final long sg) {
final long[] rest = new long[] { 0, 1 };
long jdi = RubyDateTime.getDay(context, jd, rest);
RubyNumeric ajd = jd_to_ajd(context, jdi);
return new RubyDate(context, (RubyClass) self, ajd, rest, 0, sg);
}
private void adjustWithDayFraction(ThreadContext context, DateTime dt, final long[] rest) {
final RubyFixnum zero = RubyFixnum.zero(context.runtime);
int ival;
ival = RubyDateTime.getHour(context, zero, rest);
dt = dt.plusHours(ival);
if (rest[0] != 0) {
ival = RubyDateTime.getMinute(context, zero, rest);
dt = dt.plusMinutes(ival);
if (rest[0] != 0) {
ival = RubyDateTime.getSecond(context, zero, rest);
dt = dt.plusSeconds(ival);
final long r0 = rest[0], r1 = rest[1];
if (r0 != 0) {
long millis = ( 1000 * r0 ) / r1;
dt = dt.plusMillis((int) millis);
subMillisNum = ((1000 * r0) - (millis * r1));
subMillisDen = r1;
long gcd = i_gcd(subMillisNum, subMillisDen);
subMillisNum = subMillisNum / gcd;
subMillisDen = subMillisDen / gcd;
}
}
}
this.dt = dt;
}
@JRubyMethod(name = "valid_jd?", meta = true)
public static IRubyObject valid_jd_p(ThreadContext context, IRubyObject self, IRubyObject jd) {
return jd == context.nil ? context.fals : context.tru; // @see _valid_jd_p
}
@JRubyMethod(name = "valid_jd?", meta = true)
public static IRubyObject valid_jd_p(ThreadContext context, IRubyObject self, IRubyObject jd, IRubyObject sg) {
return jd == context.nil ? context.fals : context.tru; // @see _valid_jd_p
}
// Is +jd+ a valid Julian Day Number?
//
// If it is, returns it. In fact, any value is treated as a valid Julian Day Number.
@JRubyMethod(name = "_valid_jd?", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_jd_p(IRubyObject self, IRubyObject jd) {
return jd;
}
@JRubyMethod(name = "_valid_jd?", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_jd_p(IRubyObject self, IRubyObject jd, IRubyObject sg) {
return jd;
}
@JRubyMethod(name = "ordinal", meta = true, optional = 3)
public static RubyDate ordinal(ThreadContext context, IRubyObject self, IRubyObject[] args) {
// ordinal(y=-4712, d=1, sg=ITALY)
final int len = args.length;
final long sg = len > 2 ? val2sg(context, args[2]) : ITALY;
IRubyObject year = (len > 0) ? args[0] : RubyFixnum.newFixnum(context.runtime, -4712);
IRubyObject day = (len > 1) ? args[1] : RubyFixnum.newFixnum(context.runtime, 1);
final long[] rest = new long[] { 0, 1 };
final int d = (int) RubyDateTime.getDay(context, day, rest);
Long jd = validOrdinalImpl(year, d, sg);
if (jd == null) {
throw context.runtime.newArgumentError("invalid date");
}
return new RubyDate(context, (RubyClass) self, jd_to_ajd(context, jd), rest, 0, sg);
}
@JRubyMethod(name = "valid_ordinal?", meta = true, required = 2, optional = 1)
public static IRubyObject valid_ordinal_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 2 ? val2sg(context, args[2]) : ITALY;
final Long jd = validOrdinalImpl(args[0], args[1], sg);
return jd == null ? context.fals : context.tru;
}
static Long validOrdinalImpl(IRubyObject year, IRubyObject day, final long sg) {
return validOrdinalImpl(year, day.convertToInteger().getIntValue(), sg);
}
private static Long validOrdinalImpl(IRubyObject year, int day, final long sg) {
final int y = year.convertToInteger().getIntValue();
return DateUtils._valid_ordinal_p(y, day, sg);
}
@Deprecated // NOTE: should go away once no date.rb is using it
@JRubyMethod(name = "_valid_ordinal?", meta = true, required = 2, optional = 1, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_ordinal_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 2 ? val2sg(context, args[2]) : GREGORIAN;
final Long jd = validOrdinalImpl(args[0], args[1], sg);
return jd == null ? context.nil : RubyFixnum.newFixnum(context.runtime, jd);
}
@Deprecated // NOTE: should go away once no date.rb is using it
@JRubyMethod(name = "_valid_ordinal?", required = 2, optional = 1, visibility = Visibility.PRIVATE)
public IRubyObject _valid_ordinal_p(ThreadContext context, IRubyObject[] args) {
return RubyDate._valid_ordinal_p(context, null, args);
}
@JRubyMethod(name = "commercial", meta = true, optional = 4)
public static RubyDate commercial(ThreadContext context, IRubyObject self, IRubyObject[] args) {
// commercial(y=-4712, w=1, d=1, sg=ITALY)
final int len = args.length;
final long sg = len > 3 ? val2sg(context, args[3]) : ITALY;
IRubyObject year = (len > 0) ? args[0] : RubyFixnum.newFixnum(context.runtime, -4712);
IRubyObject week = (len > 1) ? args[1] : RubyFixnum.newFixnum(context.runtime, 1);
IRubyObject day = (len > 2) ? args[2] : RubyFixnum.newFixnum(context.runtime, 1);
Long jd = validCommercialImpl(year, week, day, sg);
if (jd == null) {
throw context.runtime.newArgumentError("invalid date");
}
return new RubyDate(context, (RubyClass) self, jd_to_ajd(context, jd), 0, sg);
}
@JRubyMethod(name = "valid_commercial?", meta = true, required = 3, optional = 1)
public static IRubyObject valid_commercial_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 3 ? val2sg(context, args[3]) : ITALY;
final Long jd = validCommercialImpl(args[0], args[1], args[2], sg);
return jd == null ? context.fals : context.tru;
}
static Long validCommercialImpl(IRubyObject year, IRubyObject week, IRubyObject day, final long sg) {
final int y = year.convertToInteger().getIntValue();
int w = week.convertToInteger().getIntValue();
int d = day.convertToInteger().getIntValue();
return DateUtils._valid_commercial_p(y, w, d, sg);
}
@Deprecated // NOTE: should go away once no date.rb is using it
@JRubyMethod(name = "_valid_commercial?", meta = true, required = 3, optional = 1, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_commercial_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 3 ? val2sg(context, args[3]) : GREGORIAN;
final Long jd = validCommercialImpl(args[0], args[1], args[2], sg);
return jd == null ? context.nil : RubyFixnum.newFixnum(context.runtime, jd);
}
@Deprecated // NOTE: should go away once no date.rb is using it
@JRubyMethod(name = "_valid_weeknum?", meta = true, required = 4, optional = 1, visibility = Visibility.PRIVATE)
public static IRubyObject _valid_weeknum_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 4 ? val2sg(context, args[4]) : GREGORIAN;
final int y = args[0].convertToInteger().getIntValue();
final int w = args[1].convertToInteger().getIntValue();
final int d = args[2].convertToInteger().getIntValue();
final int f = args[3].convertToInteger().getIntValue();
final Long jd = DateUtils._valid_weeknum_p(y, w, d, f, sg);
return jd == null ? context.nil : RubyFixnum.newFixnum(context.runtime, jd);
}
/**
# Create a new Date object representing today.
#
# +sg+ specifies the Day of Calendar Reform.
**/
@JRubyMethod(meta = true)
public static RubyDate today(ThreadContext context, IRubyObject self) { // sg=ITALY
return new RubyDate(context.runtime, (RubyClass) self, new DateTime(CHRONO_ITALY).withTimeAtStartOfDay());
}
@JRubyMethod(meta = true)
public static RubyDate today(ThreadContext context, IRubyObject self, IRubyObject sg) {
final long start = val2sg(context, sg);
return new RubyDate(context.runtime, (RubyClass) self, new DateTime(getChronology(context, start, 0)).withTimeAtStartOfDay(), 0, start);
}
@JRubyMethod(name = "_valid_civil?", meta = true, required = 3, optional = 1)
public static IRubyObject _valid_civil_p(ThreadContext context, IRubyObject self, IRubyObject[] args) {
final long sg = args.length > 3 ? val2sg(context, args[3]) : GREGORIAN;
final Long jd = validCivilImpl(args[0], args[1], args[2], sg);
return jd == null ? context.nil : RubyFixnum.newFixnum(context.runtime, jd);
}
@Deprecated // NOTE: should go away once no date.rb is using it
@JRubyMethod(name = "_valid_civil?", required = 3, optional = 1, visibility = Visibility.PRIVATE)
public IRubyObject _valid_civil_p(ThreadContext context, IRubyObject[] args) {
return RubyDate._valid_civil_p(context, null, args);
}
public DateTime getDateTime() { return dt; }
@Override
public boolean equals(Object other) {
if (other instanceof RubyDate) {
return equals((RubyDate) other);
}
return false;
}
public final boolean equals(RubyDate that) {
return this.start == that.start && this.dt.equals(that.dt) &&
this.subMillisNum == that.subMillisNum && this.subMillisDen == that.subMillisDen;
}
@Override
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(IRubyObject other) throws RuntimeException {
if (other instanceof RubyDate) {
return getRuntime().newBoolean( equals((RubyDate) other) );
}
return getRuntime().getFalse();
}
@Override
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) throws RaiseException {
if (other instanceof RubyDate) {
return context.runtime.newFixnum(cmp((RubyDate) other));
}
// other (Numeric) - 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.
if (other instanceof RubyNumeric) {
final IRubyObject ajd = ajd(context);
return context.sites.Numeric.op_cmp.call(context, ajd, ajd, other);
}
return fallback_cmp(context, other);
}
private int cmp(final RubyDate that) {
int cmp = this.dt.compareTo(that.dt); // 0, +1, -1
if (cmp == 0) {
if (this.subMillisDen == 1 && that.subMillisDen == 1) {
long subNum1 = this.subMillisNum;
long subNum2 = that.subMillisNum;
if (subNum1 < subNum2) return -1;
if (subNum1 > subNum2) return +1;
return 0;
}
return cmpSubMillis(that);
}
return cmp;
}
private int cmpSubMillis(final RubyDate that) {
ThreadContext context = getRuntime().getCurrentContext();
RubyNumeric diff = subMillisDiff(context, that);
return diff.isZero() ? 0 : ( Numeric.f_negative_p(context, diff) ? -1 : +1 );
}
private IRubyObject fallback_cmp(ThreadContext context, IRubyObject other) {
RubyArray res;
try {
res = (RubyArray) other.callMethod(context, "coerce", this);
}
catch (RaiseException ex) {
if (ex.getException() instanceof RubyNoMethodError) return context.nil;
throw ex;
}
return f_cmp(context, res.eltInternal(0), res.eltInternal(1));
}
@Override
public int hashCode() {
return (int) (dt.getMillis() ^ dt.getMillis() >>> 32);
}
@JRubyMethod
public RubyFixnum hash(ThreadContext context) {
return hashImpl(context.runtime);
}
private RubyFixnum hashImpl(final Ruby runtime) {
return new RubyFixnum(runtime, this.dt.getMillis());
}
@Override
public RubyFixnum hash() {
return hashImpl(getRuntime());
}
@JRubyMethod // Get the date as a Julian Day Number.
public RubyFixnum jd(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, getJulianDayNumber());
}
public final long getJulianDayNumber() {
return DateTimeUtils.toJulianDayNumber(dt.getMillis() + off * 1000);
}
@JRubyMethod(name = "julian?")
public RubyBoolean julian_p(ThreadContext context) {
return RubyBoolean.newBoolean(context.runtime, isJulian());
}
@JRubyMethod(name = "gregorian?")
public RubyBoolean gregorian_p(ThreadContext context) {
return RubyBoolean.newBoolean(context.runtime, ! isJulian());
}
public final boolean isJulian() {
// JULIAN.<=>(numeric) => +1
if (start == JULIAN) return true;
// GREGORIAN.<=>(numeric) => -1
if (start == GREGORIAN) return false;
return getJulianDayNumber() < start;
}
// Get the date as an Astronomical Julian Day Number.
@JRubyMethod
public IRubyObject ajd(ThreadContext context) {
final Ruby runtime = context.runtime;
long num = 210_866_760_000_000l + dt.getMillis();
// + subMillis :
if (subMillisDen == 1) {
num += subMillisNum;
return RubyRational.newInstance(context, RubyFixnum.newFixnum(runtime, num), DAY_MS(context));
}
RubyNumeric val = (RubyNumeric) RubyFixnum.newFixnum(runtime, num).op_plus(context, subMillis(runtime));
return RubyRational.newRationalConvert(context, val, DAY_MS(context));
}
// Get the date as an Astronomical Modified Julian Day Number.
@JRubyMethod
public IRubyObject amjd(ThreadContext context) { // ajd - MJD_EPOCH_IN_AJD
final RubyRational _MJD_EPOCH_IN_AJD = RubyRational.newRational(context.runtime, -4800001, 2); // 1858-11-17
return _MJD_EPOCH_IN_AJD.op_plus(context, ajd(context));
}
// When is the Day of Calendar Reform for this Date object?
@JRubyMethod
public IRubyObject start(ThreadContext context) {
Chronology chrono = dt.getChronology();
if (chrono instanceof GregorianChronology) {
return getMetaClass().getConstant("GREGORIAN"); // Date::GREGORIAN (-Date::Infinity)
}
if (chrono instanceof JulianChronology) {
return getMetaClass().getConstant("JULIAN"); // Date::JULIAN (+Date::Infinity)
}
long cutover = DateTimeUtils.toJulianDayNumber(((GJChronology) chrono).getGregorianCutover().getMillis());
return new RubyFixnum(context.runtime, cutover);
}
final int adjustJodaYear(int year) {
if (year < 0 && isJulian()) {
// Joda-time returns -x for year x BC in JulianChronology (so there is no year 0),
// while date.rb returns -x+1, following astronomical year numbering (with year 0)
return ++year;
}
return year;
}
@JRubyMethod(name = "year")
public RubyInteger year(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, adjustJodaYear(dt.getYear()));
}
@JRubyMethod(name = "yday")
public RubyInteger yday(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getDayOfYear());
}
@JRubyMethod(name = "mon", alias = "month")
public RubyInteger mon(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getMonthOfYear());
}
@JRubyMethod(name = "mday", alias = "day")
public RubyInteger mday(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getDayOfMonth());
}
// Get any fractional day part of the date.
@JRubyMethod(name = "day_fraction")
public RubyNumeric day_fraction(ThreadContext context) { // Rational(millis, 86_400_000)
long ms = dt.getSecondOfDay() * 1000L + dt.getMillisOfSecond();
if (subMillisDen == 1) {
return (RubyNumeric) RubyRational.newRationalCanonicalize(context, ms + subMillisNum, DAY_MS);
}
final Ruby runtime = context.runtime;
RubyNumeric sum = RubyRational.newRational(runtime, ms, 1).op_plus(context, subMillis(runtime));
return sum.convertToRational().op_div(context, RubyFixnum.newFixnum(runtime, DAY_MS));
}
@JRubyMethod(name = "hour", visibility = Visibility.PRIVATE)
public RubyInteger hour(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getHourOfDay());
}
@JRubyMethod(name = "min", alias = "minute", visibility = Visibility.PRIVATE)
public RubyInteger minute(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getMinuteOfHour());
}
@JRubyMethod(name = "sec", alias = "second", visibility = Visibility.PRIVATE)
public RubyInteger second(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getSecondOfMinute());
}
@JRubyMethod(name = "sec_fraction", alias = "second_fraction", visibility = Visibility.PRIVATE)
public RubyNumeric sec_fraction(ThreadContext context) {
long ms = dt.getMillisOfSecond();
if (subMillisDen == 1) {
return (RubyNumeric) RubyRational.newRationalCanonicalize(context, ms + subMillisNum, 1000);
}
final Ruby runtime = context.runtime;
RubyNumeric sum = RubyRational.newRational(runtime, ms, 1).op_plus(context, subMillis(runtime));
return sum.convertToRational().op_div(context, RubyFixnum.newFixnum(runtime, 1000));
}
@JRubyMethod
public RubyInteger cwyear(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, adjustJodaYear(dt.getWeekyear()));
}
@JRubyMethod
public RubyInteger cweek(ThreadContext context) {
return RubyFixnum.newFixnum(context.runtime, dt.getWeekOfWeekyear());
}
@JRubyMethod
public RubyInteger cwday(ThreadContext context) {
// Monday is commercial day-of-week 1; Sunday is commercial day-of-week 7.
return RubyFixnum.newFixnum(context.runtime, dt.getDayOfWeek());
}
@JRubyMethod
public RubyInteger wday(ThreadContext context) {
// Sunday is day-of-week 0; Saturday is day-of-week 6.
return RubyFixnum.newFixnum(context.runtime, dt.getDayOfWeek() % 7);
}
private static final ByteList UTC_ZONE = new ByteList(new byte[] { '+','0','0',':','0','0' }, false);
@JRubyMethod(visibility = Visibility.PRIVATE)
public RubyString zone(ThreadContext context) {
// MRI: m_zone
if (this.off == 0) {
return RubyString.newUsAsciiStringShared(context.runtime, UTC_ZONE);