-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDate.java
More file actions
1564 lines (1291 loc) · 64 KB
/
Date.java
File metadata and controls
1564 lines (1291 loc) · 64 KB
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
package javaxt.utils;
import java.util.*;
import java.time.*;
import java.time.temporal.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
//******************************************************************************
//** Date Utils
//******************************************************************************
/**
* Used to parse, format, and compute dates
*
******************************************************************************/
public class Date implements Comparable {
private Locale currentLocale = Locale.getDefault();
private java.util.TimeZone timeZone = Calendar.getInstance().getTimeZone();
private java.util.Date currDate;
public static final String INTERVAL_MILLISECONDS = "S";
public static final String INTERVAL_SECONDS = "s";
public static final String INTERVAL_MINUTES = "m";
public static final String INTERVAL_HOURS = "h";
public static final String INTERVAL_DAYS = "d";
public static final String INTERVAL_WEEKS = "w";
public static final String INTERVAL_MONTHS = "m";
public static final String INTERVAL_YEARS = "y";
private static final HashMap<String, String> timezones = new HashMap<>();
private static final String[] SupportedFormats = new String[] {
"EEE, d MMM yyyy HH:mm:ss z", // Mon, 7 Jun 1976 13:02:09 EST
"EEE, dd MMM yyyy HH:mm:ss z", // Mon, 07 Jun 1976 13:02:09 EST
"EEE, dd MMM yyyy HH:mm:ss", // Mon, 07 Jun 1976 13:02:09
"EEE MMM dd HH:mm:ss z yyyy", // Mon Jun 07 13:02:09 EST 1976
"EEE MMM d HH:mm:ss z yyyy", // Mon Jun 7 13:02:09 EST 1976
"EEE MMM dd HH:mm:ss yyyy", // Mon Jun 07 13:02:09 1976
"EEE MMM d HH:mm:ss yyyy", // Mon Jun 7 13:02:09 1976
"EEE MMM dd yyyy HH:mm:ss z", //"Mon Jun 07 2013 00:00:00 GMT-0500 (Eastern Standard Time)"
"yyyy-MM-dd HH:mm:ss.SSS Z", // 1976-06-07 13:02:36.000 America/New_York
"yyyy-MM-dd HH:mm:ss.SSSZ", // 1976-06-07 01:02:09.000-0500
"yyyy-MM-dd HH:mm:ss.SSS", // 1976-06-07 01:02:09.000
"yyyy-MM-dd HH:mm:ss Z", // 1976-06-07 13:02:36 America/New_York
"yyyy-MM-dd HH:mm:ssZ", // 1976-06-07 13:02:36-0500
"yyyy-MM-dd HH:mm:ss", // 1976-06-07 01:02:09
"yyyy:MM:dd HH:mm:ss", // 1976:06:07 01:02:09 (exif metadata)
"yyyy-MM-dd-HH:mm:ss.SSS", // 1976-06-07-01:02:09.000
"yyyy-MM-dd-HH:mm:ss", // 1976-06-07-01:02:09
//"yyyy-MM-ddTHH:mm:ss.SSS", // 1976-06-07T01:02:09.000
//"yyyy-MM-ddTHH:mm:ss", // 1976-06-07T01:02:09
"dd-MMM-yyyy h:mm:ss a", // 07-Jun-1976 1:02:09 PM
"dd-MMM-yy h:mm:ss a", // 07-Jun-76 1:02:09 PM
//"d-MMM-yy h:mm:ss a", // 7-Jun-76 1:02:09 PM
"yyyy-MM-dd HH:mm Z", // 1976-06-07 13:02 America/New_York"
"yyyy-MM-dd HH:mmZ", // 1976-06-07T13:02-0500
"yyyy-MM-dd HH:mm", // 1976-06-07T13:02
"yyyy-MM-dd", // 1976-06-07
"dd-MMM-yy", // 07-Jun-76
//"d-MMM-yy", // 7-Jun-76
"dd-MMM-yyyy", // 07-Jun-1976
"MMMMMM d, yyyy", // June 7, 1976
"M/d/yy h:mm:ss a", // 6/7/1976 1:02:09 PM
"M/d/yy h:mm a", // 6/7/1976 1:02 PM
"MM/dd/yy HH:mm:ss Z", // 06/07/1976 13:02:09 America/New_York
"MM/dd/yy HH:mm:ss", // 06/07/1976 13:02:09
"MM/dd/yy HH:mm Z", // 06/07/1976 13:02 America/New_York
"MM/dd/yy HH:mm", // 06/07/1976 13:02
"MM/dd/yyyy HH:mm:ss Z", // 06/07/1976 13:02:09 America/New_York
"MM/dd/yyyy HH:mm:ss", // 06/07/1976 13:02:09
"MM/dd/yyyy HH:mm Z", // 06/07/1976 13:02 America/New_York
"MM/dd/yyyy HH:mm", // 06/07/1976 13:02
"M/d/yy", // 6/7/76
"MM/dd/yyyy", // 06/07/1976
"M/d/yyyy", // 6/7/1976
"yyyyMMddHHmmssSSS", // 19760607130200000
"yyyyMMddHHmmss", // 19760607130200
"yyyyMMdd" // 19760607
};
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using the current time
*/
public Date(){
currDate = new java.util.Date();
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a java.util.Date
*/
public Date(java.util.Date date){
if (date==null) throw new IllegalArgumentException("Date is null.");
currDate = date;
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a java.util.Calendar
*/
public Date(Calendar calendar){
if (calendar==null) throw new IllegalArgumentException("Calendar is null.");
currDate = calendar.getTime();
timeZone = calendar.getTimeZone();
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a java.time.LocalDate
*/
public Date(java.time.LocalDate date){
if (date==null) throw new IllegalArgumentException("Date is null.");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, date.getYear());
cal.set(Calendar.MONTH, date.getMonthValue()-1);
cal.set(Calendar.DAY_OF_MONTH, date.getDayOfMonth());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
currDate = cal.getTime();
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a timestamp (in milliseconds)
* since 1/1/1970.
*/
public Date(long milliseconds){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milliseconds);
currDate = cal.getTime();
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a String representation of a
* date. Supports multiple common date formats.
*/
public Date(String date) throws ParseException {
try{
//Loop through all known date formats and try to convert the string to a date
for (String format : SupportedFormats){
if (format.endsWith("Z")){
//Special Case: Java fails to parse the "T" in strings like
//"1976-06-07T01:02:09.000" and "1976-06-07T13:02-0500"
int idx = date.indexOf("T");
if (idx==10 && format.startsWith("yyyy-MM-dd HH:mm")){
date = date.substring(0, idx) + " " + date.substring(idx+1);
}
if (date.endsWith("Z") && date.length()==format.length()){
//If the date literally ends with the letter "Z", then the
//date is probably referencing "Zulu" timezone (i.e. UTC).
//Example: "1976-06-07 00:00:00Z". Java doesn't understand
//what the "Z" timezone is so we'll replace the "Z" with
//"UTC".
date = date.substring(0, date.length()-1) + "UTC";
}
else{
//Check if the timezone offset is specified in "+/-HH:mm"
//format (e.g. "2018-01-17T01:00:35+07:00"). If so, update
//the timezone offset by removing the colon.
if (date.length()>=format.length()){
int len = format.length()-1;
String tz = date.substring(len);
if (tz.length()==6){
String a = tz.substring(0,1);
if ((a.equals("-") || a.equals("+")) && tz.indexOf(":")==3){
tz = tz.replace(":", "");
date = date.substring(0, len) + tz;
}
}
}
}
}
try{
currDate = parseDate(date, format);
return;
}
catch(ParseException e){
}
}
}
catch(Exception e){
}
//If we're still here, throw an exception
throw new ParseException("Failed to parse date: " + date, 0);
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of date using a date string. The format string is
* used to create a SimpleDateFormat to parse the input date string.
*/
public Date(String date, String format) throws ParseException {
currDate = parseDate(date, format);
}
//**************************************************************************
//** setDate
//**************************************************************************
/** Used to update the current date using a date string. The format parameter
* is used to create a SimpleDateFormat to parse the input date string.
*/
public javaxt.utils.Date setDate(String date, String format) throws ParseException {
currDate = parseDate(date, format);
return this;
}
//**************************************************************************
//** setDate
//**************************************************************************
/** Used to update the current date using a predefined java.util.Date
*/
public javaxt.utils.Date setDate(java.util.Date date){
currDate = date;
return this;
}
//**************************************************************************
//** setLocale
//**************************************************************************
/** Used to update the current local
*/
public javaxt.utils.Date setLocale(Locale locale){
this.currentLocale = locale;
return this;
}
//**************************************************************************
//** getLocale
//**************************************************************************
/** Returns the current local
*/
public Locale getLocale(){
return currentLocale;
}
//**************************************************************************
//** parseDate
//**************************************************************************
/** Attempts to convert a String to a Date via the user-supplied Format
*/
private java.util.Date parseDate(String date, String format) throws ParseException {
if (date!=null){
date = date.trim();
if (date.length()==0) date = null;
}
if (date==null) throw new ParseException("Date is null.", 0);
SimpleDateFormat formatter = new SimpleDateFormat(format, currentLocale);
if (timeZone!=null) formatter.setTimeZone(timeZone);
try{
java.util.Date d = formatter.parse(date);
timeZone = formatter.getTimeZone();
return d;
}
catch(java.text.ParseException e){
//Parse the error. If it's a time zone issue, try to resolve it.
int zIndex = format.toUpperCase().indexOf("Z");
if (zIndex>0){
int errorOffset = e.getErrorOffset();
String tz = null;
if (errorOffset < format.length()){
//Check if the parser choked on the timezone format
String ch = format.substring(errorOffset, errorOffset+1);
if (ch.equalsIgnoreCase("Z") && date.length()>errorOffset){
tz = date.substring(errorOffset);
date = date.substring(0, errorOffset-1);
format = format.substring(0, errorOffset-1);
}
}
else if (errorOffset>format.length()){
//Special Case: "Fri Jan 04 2013 00:00:00 GMT-0500 (Eastern Standard Time)"
tz = date.substring(zIndex);
date = date.substring(0, zIndex-1);
format = format.substring(0, zIndex-1);
}
if (tz!=null){
try{
java.util.TimeZone zone = getTimeZone(tz);
if (zone!=null){
timeZone = zone;
formatter = new SimpleDateFormat(format, currentLocale);
formatter.setTimeZone(timeZone);
return formatter.parse(date);
}
}
catch(Exception ex){
}
}
}
throw e;
}
}
//**************************************************************************
//** setTimeZone
//**************************************************************************
/** Used to set the current time zone. The time zone is used when comparing
* and formatting dates.
* @param timeZone Name of the time zone (e.g. "UTC", "EDT", etc.)
* @param preserveTimeStamp Flag used to indicate whether to preserve the
* timestamp when changing time zones. Normally, when updating the timezone,
* the timestamp is updated to the new timezone. For example, if the current
* time is 4PM EST and you wish to switch to UTC, the timestamp would be
* updated to 8PM. The preserveTimeStamp flag allows users to preserve the
* the timestamp so that the timestamp remains fixed at 4PM.
*/
public javaxt.utils.Date setTimeZone(String timeZone, boolean preserveTimeStamp){
return setTimeZone(getTimeZone(timeZone), preserveTimeStamp);
}
//**************************************************************************
//** setTimeZone
//**************************************************************************
/** Used to set the current time zone. The time zone is used when comparing
* and formatting dates.
* @param timeZone Time zone (e.g. "UTC", "EDT", etc.)
* @param preserveTimeStamp Flag used to indicate whether to preserve the
* timestamp when changing time zones. Normally, when updating the timezone,
* the timestamp is updated to the new timezone. For example, if the current
* time is 4PM EST and you wish to switch to UTC, the timestamp would be
* updated to 8PM. The preserveTimeStamp flag allows users to preserve the
* the timestamp so that the timestamp remains fixed at 4PM.
*/
public javaxt.utils.Date setTimeZone(java.util.TimeZone timeZone, boolean preserveTimeStamp){
if (timeZone==null) return this;
if (preserveTimeStamp){
Calendar cal = Calendar.getInstance(timeZone, currentLocale);
cal.set(Calendar.YEAR, this.getYear());
cal.set(Calendar.MONTH, this.getMonth()-1);
cal.set(Calendar.DAY_OF_MONTH, this.getDay());
cal.set(Calendar.HOUR_OF_DAY, this.getHour());
cal.set(Calendar.MINUTE, this.getMinute());
cal.set(Calendar.SECOND, this.getSecond());
cal.set(Calendar.MILLISECOND, this.getMilliSecond());
currDate = cal.getTime();
}
//Do this last! Otherwise the getHour(), getMinute(), etc will be off...
this.timeZone = timeZone;
return this;
}
//**************************************************************************
//** setTimeZone
//**************************************************************************
/** Used to set the current time zone. The time zone is used when comparing
* and formatting dates.
* @param timeZone Name of the time zone (e.g. "UTC", "EST", etc.)
*/
public javaxt.utils.Date setTimeZone(String timeZone){
return setTimeZone(timeZone, false);
}
//**************************************************************************
//** setTimeZone
//**************************************************************************
/** Used to set the current time zone. The time zone is used when comparing
* and formatting dates.
*/
public javaxt.utils.Date setTimeZone(java.util.TimeZone timeZone){
return setTimeZone(timeZone, false);
}
//**************************************************************************
//** getTimeZone
//**************************************************************************
/** Returns the current time zone. The time zone is used when comparing
* and formatting dates.
*/
public java.util.TimeZone getTimeZone(){
return timeZone;
}
public int hashCode(){
return currDate.hashCode();
}
//**************************************************************************
//** toString
//**************************************************************************
/** Returns the current date as a String in the following format:
* "EEE MMM dd HH:mm:ss z yyyy"
*/
public String toString(){
return toString("EEE MMM dd HH:mm:ss z yyyy");
}
//**************************************************************************
//** toString
//**************************************************************************
/** Used to format the current date into a string.
* @param format Pattern used to format the date (e.g. "MM/dd/yyyy hh:mm a",
* "EEE MMM dd HH:mm:ss z yyyy", etc). Please refer to the
* java.text.SimpleDateFormat class for more information.
*/
public String toString(String format){
SimpleDateFormat currFormatter = new SimpleDateFormat(format, currentLocale);
currFormatter.setTimeZone(timeZone==null ? Calendar.getInstance().getTimeZone() : timeZone);
return currFormatter.format(currDate);
}
//**************************************************************************
//** toString
//**************************************************************************
/** Used to format the current date into a string in a given timezone.
* @param timeZone Name of the time zone (e.g. "UTC", "EST", etc.). Note
* that this parameter does not alter the current date in any way. This
* parameter is simply used for the output string. Use the setTimeZone()
* method to change the timezone for the current date.
*/
public String toString(String format, String timeZone){
return this.toString(format, getTimeZone(timeZone));
}
//**************************************************************************
//** format
//**************************************************************************
/** Used to format the current date into a string.
*/
public String toString(String format, java.util.TimeZone timeZone){
SimpleDateFormat currFormatter =
new SimpleDateFormat(format, currentLocale);
if (timeZone!=null) currFormatter.setTimeZone(timeZone);
return currFormatter.format(currDate);
}
//**************************************************************************
//** format
//**************************************************************************
/** Used to format the current date into a string. Same as toString(format).
*/
public String format(String format){
return toString(format);
}
//**************************************************************************
//** toISOString
//**************************************************************************
/** Returns the date in ISO 8601 format (e.g. "2013-01-04T05:00:00.000Z").
* Note that ISO dates are in UTC.
*/
public String toISOString(){
return toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "UTC");
}
//**************************************************************************
//** toLong
//**************************************************************************
/** Returns a long integer used to represent the Date in the following
* format: "yyyyMMddHHmmssSSS". The time zone is automatically set to UTC.
* This is useful for perform simple date comparisons and storing dates
* in a database as integers (e.g. SQLite). Here's an example of how to
* go from a date to a long and a long to a date:
<pre>
javaxt.utils.Date orgDate = new javaxt.utils.Date();
Long l = orgDate.toLong(); //"yyyyMMddHHmmssSSS" formatted long in UTC
javaxt.utils.Date newDate = new javaxt.utils.Date(l+"");
newDate.setTimeZone("UTC", true);
System.out.println(newDate);
</pre>
* Note that this method is different from the getTime() method which
* returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
*/
public long toLong(){
Date d = this.clone();
d.setTimeZone("UTC");
return Long.parseLong(d.toString("yyyyMMddHHmmssSSS"));
}
// //**************************************************************************
// //** toInt
// //**************************************************************************
// /** Returns an integer used to represent the Date in the following format:
// * "yyyyMMdd". The time zone is automatically set to UTC. Here's an example
// * of how to go from a date to an int and an int to a date:
// <pre>
// javaxt.utils.Date orgDate = new javaxt.utils.Date();
// int i = orgDate.toInt(); //"yyyyMMdd" formatted integer in UTC
// javaxt.utils.Date newDate = new javaxt.utils.Date(i+"");
// newDate.setTimeZone("UTC", true);
// System.out.println(newDate);
// </pre>
// */
// public int toInt(){
// Date d = this.clone();
// d.setTimeZone("UTC");
// return Integer.parseInt(d.toString("yyyyMMdd"));
// }
//**************************************************************************
//** clone
//**************************************************************************
/** Creates a copy of this object. Any modifications to the clone, will not
* affect the original.
*/
public Date clone(){
return new Date(getCalendar());
}
//**************************************************************************
//** equals
//**************************************************************************
/** Used to compare dates and determine whether they are equal.
* @param obj Accepts a java.util.Date, a javaxt.utils.Date, or a String.
*/
public boolean equals(Object obj){
if (obj==null) return false;
if (obj instanceof javaxt.utils.Date){
return ((javaxt.utils.Date) obj).getDate().equals(currDate);
}
else if (obj instanceof java.util.Date){
return ((java.util.Date) obj).equals(currDate);
}
else if (obj instanceof String){
try{
return new javaxt.utils.Date((String) obj).equals(currDate);
}
catch(ParseException e){}
}
return false;
}
//**************************************************************************
//** FormatDate
//**************************************************************************
private String FormatDate(java.util.Date date, String OutputFormat){
SimpleDateFormat formatter =
new SimpleDateFormat(OutputFormat, currentLocale);
if (timeZone != null) formatter.setTimeZone(timeZone);
return formatter.format(date);
}
//**************************************************************************
//** compareTo
//**************************************************************************
/** Used to compare dates. Returns the number of intervals between two dates.
* If the given date is in the future, returns a negative value. If the
* given date is in the past, returns a positive value.
* @param units Units of measure (e.g. hours, minutes, seconds, weeks,
* months, years, etc.)
*/
public long compareTo(javaxt.utils.Date date, String units){
return diff(currDate, date.getDate(), units);
}
//**************************************************************************
//** compareTo
//**************************************************************************
/** Used to compare dates. Returns the number of intervals between two dates
* @param units Units of measure (e.g. hours, minutes, seconds, weeks,
* months, years, etc.)
*/
public long compareTo(java.util.Date date, String units){
return diff(currDate, date, units);
}
//**************************************************************************
//** diff
//**************************************************************************
/** Used to compare dates. Returns a long value representing the difference
* between the dates for the given unit of measure. Note that this method
* will "round down" differences between dates.
* @param interval Unit of measure. Supports seconds, minutes, hours, days,
* weeks, months, and years.
*/
private long diff(java.util.Date date1, java.util.Date date2, String interval){
LocalDate s = new Date(date2).getLocalDate();
LocalDate e = new Date(date1).getLocalDate();
double div = 1;
if (interval.equals("S") || interval.toLowerCase().startsWith("sec")){
div = 1000L;
//return ChronoUnit.SECONDS.between(s, e);
}
if (interval.equals("m") || interval.toLowerCase().startsWith("min")){
div = 60L * 1000L;
//return ChronoUnit.MINUTES.between(s, e);
}
if (interval.equals("H") || interval.toLowerCase().startsWith("h")){
div = 60L * 60L * 1000L;
//return ChronoUnit.HOURS.between(s, e);
}
if (interval.equals("d") || interval.toLowerCase().startsWith("d")){
div = 24L * 60L * 60L * 1000L;
//return ChronoUnit.DAYS.between(s, e);
}
if (interval.equals("w") || interval.toLowerCase().startsWith("w")){
div = 7L * 24L * 60L * 60L * 1000L;
//return ChronoUnit.WEEKS.between(s, e);
}
if (interval.equals("M") || interval.toLowerCase().startsWith("mon")){
//div = 30L * 24L * 60L * 60L * 1000L;
return ChronoUnit.MONTHS.between(s, e);
}
if (interval.equals("y") || interval.toLowerCase().startsWith("y")){
//div = 365L * 24L * 60L * 60L * 1000L;
return ChronoUnit.YEARS.between(s, e);
}
long d1 = date1.getTime();
long d2 = date2.getTime();
int i2 = (int)Math.abs((d1 - d2) / div);
if (date2.after(date1)){
i2 = -i2;
}
return i2;
}
//**************************************************************************
//** getMonthsBetween
//**************************************************************************
/** Returns fractional month difference between two dates. This method will
* return whole numbers (1, 2, 3, etc) if the two dates fall on the same
* day of the month (e.g. "2023-03-01" v "2023-04-01" or "2023-03-14" v
* "2023-04-14"). Returns a decimal value less than or equal to 1 (<=1)
* if the dates fall within the same month (e.g. "2024-01-01" v "2024-01-31"
* yields 1.0 and "2024-01-01" v "2024-01-30" yields 0.968). Otherwise,
* returns the number of full months between the two dates plus a
* fractional value (e.g. "2023-01-27" v "2023-02-28" yields 1.0357). The
* decimal value (numbers after the decimal point) represent fractions of a
* month. Roughly speaking, a day is 0.03 of a month.
*
* <p>
* There are some interesting results when comparing dates around the end
* of two different months. Specifically when comparing a longer month to
* shorter month. For example:
* </p>
* <ul>
* <li>"2024-01-31" v "2024-02-29" = 1 month</li>
* <li>"2023-01-31" v "2023-02-28" = 1 month</li>
* <li>"2023-12-31" v "2024-02-29" = 2 months</li>
* <li>"2022-12-31" v "2023-02-29" = 2 months</li>
* </ul>
* In these examples we are following semantic rules and are rounding down
* the differences. However, when we compare dates around the end of two
* different months if the start month is shorter, we don't round. Example:
* <ul>
* <li>"2024-04-30" v "2024-05-31" = 1 month, 1 day</li>
* <li>"2023-02-28" v "2024-02-29" = 12 months, 1 day</li>
* </ul>
*
* In these examples you can see that we are following semantic rules
* rather than straight math.
*
* <p>
* Note that you can use the compareTo() method to compare months using the
* Java standard which rounds down the difference between two months and
* does not return fractions.
* </p>
*/
public static double getMonthsBetween(javaxt.utils.Date start, javaxt.utils.Date end) {
return getMonthsBetween(start.getLocalDate(), end.getLocalDate());
}
private static double getMonthsBetween(LocalDate start, LocalDate end) {
//Check if the start date is after the end date. Swap dates as needed
boolean negate = false;
if (start.isAfter(end)){
negate = true;
LocalDate t = start;
start = end;
end = t;
}
//Check if start/end dates fall on the last of the month
boolean startIsLastDayInMonth = start.getDayOfMonth() == start.lengthOfMonth();
boolean endIsLastDayInMonth = end.getDayOfMonth() == end.lengthOfMonth();
//Calulate months between the 2 dates using Java's built-in ChronoUnit
//Note that the ChronoUnit "rounds down" the interval between the dates.
long m = ChronoUnit.MONTHS.between(start, end);
//When the 2 dates fall on the same day in the month, and the dates aren't
//on the last day of the month, simply return the value returned by the
//ChronoUnit class
int startDay = start.getDayOfMonth();
int endDay = end.getDayOfMonth();
if (startDay==endDay){
if (startIsLastDayInMonth && !endIsLastDayInMonth ||
!startIsLastDayInMonth && endIsLastDayInMonth){
//Example: 2024-11-28 2025-02-28
}
else{
return m;
}
}
//If we're still here, compute fractions
double fraction = 0.0;
if (m==0 && start.getMonthValue()==end.getMonthValue()){
//Simply compare the days of the month
fraction = (end.getDayOfMonth()-(start.getDayOfMonth()-1))/(double)end.lengthOfMonth();
}
else{
//Create new end date using the original end date. Adjust the day
//of the month to match the start date. The new date will be either
//before or after the original end date.
int maxDays = LocalDate.of(end.getYear(), end.getMonthValue(), 1).lengthOfMonth();
LocalDate e2 = LocalDate.of(end.getYear(), end.getMonthValue(), Math.min(start.getDayOfMonth(), maxDays));
if (start.getDayOfMonth()>maxDays){
//Create new date a few days after the end of the month
LocalDate d = e2.plusDays(start.getDayOfMonth()-maxDays);
//Calculate months between the start date and the new date
m = ChronoUnit.MONTHS.between(start, d);
//Calculate fraction
if (startIsLastDayInMonth && endIsLastDayInMonth){}
else{
if (!startIsLastDayInMonth){
fraction = -((start.lengthOfMonth()-start.getDayOfMonth())/(double)start.lengthOfMonth());
}
else{
fraction = -(1-((end.getDayOfMonth())/(double)maxDays));
}
}
}
else{
//Calculate months between the start date and the new end date
m = ChronoUnit.MONTHS.between(start, e2);
//Calculate fraction
if (e2.isAfter(end)){
//subtract from e2
int n = e2.getDayOfMonth()-end.getDayOfMonth();
double f = (double)n/(double)end.lengthOfMonth();
if (m==0){
fraction = 1-f;
}
else{
fraction = -f;
}
}
else if (e2.isBefore(end)){
//add from e2
int x = start.getDayOfMonth()==1 ? 1 : 0;
fraction = (end.getDayOfMonth()-(start.getDayOfMonth()-x))/(double)end.lengthOfMonth();
}
}
}
//Add months and fractions
double diff = fraction+(double)m;
//When the 2 dates fall on the the last day of the month, round up
if ((startIsLastDayInMonth && endIsLastDayInMonth) && (start.getMonthValue()>end.getMonthValue())){
diff = Math.round(diff);
}
//Return diff
return negate ? -diff : diff;
}
private static LocalDate addOrSubtractMonths(long amount, LocalDate d){
if (amount==0) return d;
if (d.getDayOfMonth() == d.lengthOfMonth()){
d = d.withDayOfMonth(1);
if (amount>0){
d = d.plusMonths(amount);
}
else{
d = d.minusMonths(-amount);
}
d = d.withDayOfMonth(d.lengthOfMonth());
}
else{
if (amount>0){
d = d.plusMonths(amount);
}
else{
d = d.minusMonths(-amount);
}
}
return d;
}
//**************************************************************************
//** isBefore
//**************************************************************************
/** Returns true if a given date is before the current date
*/
public boolean isBefore(String date) throws ParseException {
return isBefore(new javaxt.utils.Date(date));
}
//**************************************************************************
//** isBefore
//**************************************************************************
/** Returns true if a given date is before the current date
*/
public boolean isBefore(javaxt.utils.Date Date){
if (Date==null) return false;
return currDate.before(Date.getDate());
}
//**************************************************************************
//** isAfter
//**************************************************************************
/** Returns true if a given date is after the current date
*/
public boolean isAfter(String date) throws ParseException {
return isAfter(new javaxt.utils.Date(date));
}
//**************************************************************************
//** isAfter
//**************************************************************************
/** Returns true if a given date is after the current date
*/
public boolean isAfter(javaxt.utils.Date Date){
if (Date==null) return false;
return currDate.after(Date.getDate());
}
//**************************************************************************
//** add
//**************************************************************************
/** Used to update the current date by adding to (or subtracting from) the
* current date. Example:
<pre>
javaxt.utils.Date date = new javaxt.utils.Date();
System.out.println("Today is: " + date);
date.add(-1, "day");
System.out.println("Yesterday was: " + date);
</pre>
* @param units Unit of measure (e.g. hours, minutes, seconds, days, weeks,
* months, years, etc.)
*/
public javaxt.utils.Date add(int amount, String units){
Calendar cal = getCalendar();
int div = 0;
if (units.equals("S") || units.toLowerCase().startsWith("ms") || units.toLowerCase().startsWith("mil")){
div = cal.MILLISECOND;
}
else if (units.equals("s") || units.toLowerCase().startsWith("sec")){
div = cal.SECOND;
}
else if(units.equals("m") || units.toLowerCase().startsWith("min")){
div = cal.MINUTE;
}
else if (units.equals("H") || units.toLowerCase().startsWith("h")){
div = cal.HOUR_OF_DAY;
}
else if (units.toLowerCase().startsWith("d")){
div = cal.DAY_OF_YEAR;
}
else if (units.toLowerCase().startsWith("w")){
div = cal.WEEK_OF_YEAR;
}
else if (units.equals("M") || units.toLowerCase().startsWith("mon")){
div = cal.MONTH;
}
else if (units.toLowerCase().startsWith("y")){
div = cal.YEAR;
}
cal.add(div, amount);
currDate = cal.getTime();
return this;
}
//**************************************************************************
//** subtract
//**************************************************************************
/** Used to update the current date by subtracting from the current date.
* @param units Unit of measure (e.g. hours, minutes, seconds, days, weeks,
* months, years, etc.)
*/