-
Notifications
You must be signed in to change notification settings - Fork 0
/
cDateFunctions.wl
1789 lines (1304 loc) · 103 KB
/
cDateFunctions.wl
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:: *)
(* Mathematica Package *)
(* Title: cDateFunctions *)
(* Author: Benjamin Izadpanah *)
(* Copyright: Benjamin Izadpanah *)
(* Contact: ben.izd@outlook.com *)
(* Summary: This package includes functions equivalent to Wolfram Language built-in date-related functions with minimum supported options.
TimeZone,TimeSystem are not directly supported. *)
(* Context: cDateFunctions` *)
(* Context Conflict: If you used the cDateFunctions LibraryLink package (uses DLL files), cLeapYearQ will be overridden to use pure Wolfram-Language implementation. *)
(* Start Date: 2021-7 *)
(* Last Modified Date: 2021-12 *)
(* version required, because:
12.3 , "FromDateString" used in cDateBounds,cDateWithinQ,cDateOverlapsQ to support string as a start argument
12.1 , "Splice" used in cHoliday*
"DateInterval" used in cDatePlus to support it
11.0 , "Ramp" used in cCalendarRangeView to create calendrical view
10.4 , "MixedMagnitude","MixedUnit" used in cDateDifference for handling multiple types
"Highlighted" used in cCalendarRangeView,cCalendarView,cCalendarMultipleView to highlight given dates
10.3 , "LessEqualThan","GreaterEqualThan" used in cDateRange
10.2 , "Nothing" was used to generate holidays, end/beginning of months
10.0 , "Catenate" used in cDateRange,cDayRange,cDayCount,cHoliday*
"TimeObject" was used to be supported in different functions
"GroupBy" used in cDatePlus to handle multiple units
"AnyTrue" used in "DateWithinQ","DateOverlapsQ"
"AllTrue" used in "DateWithinQ"
"ColorQ" used to validate input in genrating hilighted calendrical views
"FirstPosition" used in "cCalendarRangeView"
"DateObject" used in many places, mainly to construct the ouput
*)
(* 81 main built-in functions used to build this package (not all the functions listed) *)
(* {Abs, AbsoluteTime, AllTrue, Alternatives, And, AnyTrue,
Append, Apply, ArrayPad, ArrayQ, Begin, BeginPackage,
BitXor, Block, Boole, Cases, Catch, Catenate, Ceiling,
Check, Circle, ClearAll, Clip, ColorQ, Complement,
ConstantArray, Count, DateInterval, DateList, DateObject,
DateRange, DateString, Defer, DeleteCases,
DeleteDuplicates, Dot, Drop, End, EndPackage, Except,
First, FirstPosition, Floor, Fold, FoldList,
FractionalPart, FreeQ, FromAbsoluteTime, FromDateString,
Graphics, GrayLevel, GreaterEqualThan, GroupBy, Head,
Highlighted, HoldComplete, Identity, If, Inset, IntegerQ,
Intersection, Join, Labeled, Last, Length, LessEqualThan,
Map, MapAt, MatchQ, Max, Message, Min, Missing,
MissingQ, MixedMagnitude, MixedUnit, Mod, Most, N,
Negative, Nest, NestWhileList, Normal, Not, Nothing,
NumberQ, Optional, Or, Partition, Pink, Positive,
Quantity, Quiet, Quotient, QuotientRemainder, Ramp,
Range, Repeated, Replace, ReplaceAll, ReplacePart, Rest,
Return, Reverse, Select, Sequence, SetAttributes, Sign,
Sort, SortBy, Span, Splice, Style, Switch,
SyntaxInformation, Table, TableForm, Take, Text,
Thickness, Thread, Throw, TimeObject, Total, Transpose,
Unevaluated, Unitize, UnitStep, With} *)
(* holidays:
1,1 - New Year day (year>=1871) - 101
1,third Monday - Martin Luther King (year>=1986) - 102
2,third Monday - Presidents' Day (22 feb for 1885 <= year < 1971, third monday for year >= 1971) - 201
5,last Monday - Memorial Day (year>=1971) - 501
6,19-juneteenth (year>=2021) - 601
7,4 - Independence Day (year>=1941) - 701
9,first monday - Labor Day (year>=1894) - 901
10,second Monday - Columbus Day (year>=1971) - 1001
10,12 - Columnus Day (1936<year<1971) - 1001
10,fourth monday - Veterans Day (1977>=year>=1971) - 1101
11,11 - Veterans Day (year>=1938 not in 1977>=year>=1971) - 1101
11,fourth Thursday - Thanksgiving (year>=1863) - 1102
12,25 - Christmas Day (year>=1871) - 1201
Source: www.timeanddate.com and www.britannica.com *)
BeginPackage["cDateFunctions`"];
(* ::Subsection:: *)
(*cLeapYearValue*)
cLeapYearQ::usage="Alternative to Mathematica built-in LeapYearQ.";
cLeapYearQ::invalidArgument="The argument `1` is not a valid day/list of days.";
SyntaxInformation[cLeapYearQ]={"ArgumentsPattern"->{_}};
ClearAll[cBusinessDayQ,cCurrentDate,cDateBounds,cDateDifference,cDateRange,
cDateWithinQ, cDayCount, cDateOverlapsQ,cDatePlus,cDayMatchQ, cDayName,
cDayRound,cDayPlus, cDayRange,cPreviousDate, cNextDate,cHolidayName,cLeapYearQ,cCalendarView,cCalendarRangeView,cCalendarMultipleView];
Begin["`Private`"];
ClearAll[cAddDayOff, cAddDayWithPattern, cAddListDate, cAddListDateList, cAddMonth, cAddMonthList, cAddYear, cAddYearList,
cBeginningOfMonthRange, cCalculateDateLength,
cCalculateDays, cCalculateNumberOfDays, cConvertUnit, cCustomDateList, cDateBoundsCore,
cDateDifferenceCore, cDateDifferenceIntegerCore, cDateOverlapComparison, cDatePlusNest, cDatePlusNestCore,
cDatePlusValue, cDatePrecision, cDateWhitinComparison, cDayCountCore,
cDayNameIndex, cDayNameValue, cDayRangeValue,cCircleAround,allowedHighlightsTypes,
cDayRoundBackwardValue, cDayRoundCore, cDayRoundValue, cEndOfMonthRange, cHolidayDaysFilter, cHolidayDaysGenerate,
cHolidayDaysToAbsolute, cHolidayNameCore, cHolidayQCore, cHolidayRange, cHolidayRangeCore, cHolidayYear,
cLeapYearValue, cMergeUnits, cMonthList, cNextDateCore, cPreviousDateCore, cQuantityToPair,
cUnitToQuantityUnit, cUnitValue,cConvertResultFrom,cNextHoliday,cPreviousHoliday,cCalendarCore,
cCalendarViewCore,cMapAt,cMapAtHighlight,cNumberDecomposeForTimeObject,cMonthListWithDay,yearDifference,monthDifference,quarterDifference,cHolidayQ];
(* cLeapYearValue[{2019, 2020, 2021}] -> {0, 1, 0} *)
cLeapYearValue[year:{__Integer}] := Block[{refinedYears=year + Boole@Negative@year},BitXor[1,Unitize[Mod[refinedYears,4]],Unitize[Mod[refinedYears,100]],Unitize[Mod[refinedYears,400]]]]
(* single start - cLeapYearQ[{2020,1,1}] *)
cLeapYearQ[year:_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{2, 6}]}]:=cLeapYearValue[{First[DateList[year]]}]==={1}
(* single year - cLeapYearQ[{2020}] *)
cLeapYearQ[year:{_Integer}] := cLeapYearValue[year] === {1}
(* repeated start cLeapYearQ[{{2020,1,1},{2021,1,1}}] *)
cLeapYearQ[years:{Repeated[_Integer|_Real,{7, Infinity}]}|{({Repeated[_Integer|_Real,{1,6}]}|_String)..}]:=Thread[cLeapYearValue[(DateList /@ years)[[All,1]]]==1]
(* pick year directly from DateObject *)
cLeapYearQ[years:{__DateObject}]:=Thread[cLeapYearValue[years[[All,1,1]]]==1]
(* convert all elements to integer *)
cLeapYearQ[years:{{_Integer|_Real}..}]:=Thread[cLeapYearValue[Apply[Floor,years,{1}]]==1]
End[];
(* ::Subsection:: *)
(*monthDifference, quarterDifference, yearDifference*)
Begin["`Private`"];
(* return AbsoluteTime - add the second argument to the first argument which is a DateList + checking to be on the exact day as the input *)
cAddListDate[date:{Repeated[_Integer|_Real,{6}]},list:{Repeated[_Integer|_Real,{6}]}]:=Block[{temp=DateList[date+list]},
If[date[[3]]==temp[[3]],AbsoluteTime[temp],AbsoluteTime[temp]-temp[[3]]*86400.]
]
(* return DateList - same as cAddListDate *)
cAddListDateList[date:{Repeated[_Integer|_Real,{6}]},list:{Repeated[_Integer|_Real,{6}]}]:=Block[{temp=DateList[date+list]},
If[date[[3]]==temp[[3]],temp,DateList[temp-{0,0,temp[[3]],0,0,0}]]
]
(* specialized cases of cAddListDate/cAddListDateList *)
(* date should have in-bound DateList values *)
cAddMonth[date:{Repeated[_Integer|_Real,{6}]},month_Integer]:=cAddListDate[date,{0,month(* +Echo@Switch[{First@date,First@date+Quotient[month,12,1]},{_?Negative, _?(Not@*Negative)},12,{_?Positive, _?Negative},-12,_,0] *),0,0,0,0}]
(* cAddMonthList[date:{Repeated[_Integer|_Real,{6}]},month_Integer]:=Block[{result=cAddListDateList[date,{0,month,0,0,0,0}]},If[First@result==-1&&Positive[month],result+{1,0,0,0,0,0},result]] *)
cAddMonthList[date:{Repeated[_Integer|_Real,{6}]},month_Integer]:=cAddListDateList[date,{0,month,0,0,0,0}]
cAddYear[date:{Repeated[_Integer|_Real,{6}]},year_Integer]:=cAddListDate[date,{year+Switch[{First@date, First@date+year},
{_?Negative, _?(Not@*Negative)}, 1,
{_?Positive, _?Negative}, - 1,
_, 0],0,0,0,0,0}]
(* cAddYear[date:{Repeated[_Integer|_Real,{6}]},year_Integer]:=cAddListDate[date,{If[First@date+year==0&&Positive[year],year+1,year],0,0,0,0,0}] *)
cAddYearList[date:{Repeated[_Integer|_Real,{6}]},year_Integer]:=cAddListDateList[date,{
year+Switch[{First@date, First@date+year},
{_?Negative, _?(Not@*Negative)}, 1,
{_?Positive, _?Negative}, - 1,
_, 0]
,0,0,0,0,0}]
(* Examples *)
(* cAddMonthList[{2020,1,31,0,0,0},1] -> {2020,2,29,0,0,0} *)
(* cAddYearList[{2020,2,29,0,0,0},1] -> {2021,2,28,0,0,0} *)
(* in monthDifference/quarterDifference/yearDifference, start start should be less than end start otherwise it'll return the negative output of reversed inputs *)
(* used inside cDateDifferenceCore *)
SetAttributes[monthDifference,Listable];
(* monthDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=-1*monthDifference[end,start] *)
monthDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=Block[{startDate=DateList[start],endDate=DateList[end],month,nextMonth,lastMonth,lastMonthList},
month=(First[endDate]-First[startDate])*12+(endDate[[2]]-startDate[[2]]);
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],month+=12];
If[cAddMonth[startDate,month]<end,month+=1];
lastMonthList=cAddMonthList[startDate,month];
lastMonth=AbsoluteTime[lastMonthList];
nextMonth=cAddMonth[lastMonthList,-1];
Return[month-(N@end-lastMonth)/(nextMonth-lastMonth)];
]
monthDifference[start:_Integer|_Real,end:_Integer|_Real]:=Block[{startDate=DateList[start],endDate=DateList[end],month,nextMonth,lastMonth,lastMonthList},
month=(First[endDate]-First[startDate])*12+(endDate[[2]]-startDate[[2]]);
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],month-=12];
If[cAddMonth[startDate,month]>end,month-=1];
lastMonthList=cAddMonthList[startDate,month];
lastMonth=AbsoluteTime[lastMonthList];
nextMonth=cAddMonth[lastMonthList,1];
Return[month+(N@end-lastMonth)/(nextMonth-lastMonth)];
]
SetAttributes[quarterDifference,Listable];
(* quarterDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=-1*quarterDifference[end,start] *)
(* quarterDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=-1*quarterDifference[end,start] *)
quarterDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=Block[{startDate=DateList[start],endDate=DateList[end],quarter,nextQuarter,lastQuarter,lastQuarterList},
quarter=Quotient[(First[endDate]-First[startDate])*12.+(endDate[[2]]-startDate[[2]]),3];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],quarter+=4];
If[cAddMonth[startDate,quarter*3]<end,quarter+=1];
lastQuarterList=cAddMonthList[startDate,quarter*3];
lastQuarter=AbsoluteTime[lastQuarterList];
nextQuarter=cAddMonth[lastQuarterList,-3];
Return[quarter-(N[end]-lastQuarter)/(nextQuarter-lastQuarter)];
]
quarterDifference[start:_Integer|_Real,end:_Integer|_Real]:=Block[{startDate=DateList[start],endDate=DateList[end],quarter,nextQuarter,lastQuarter,lastQuarterList},
quarter=Quotient[(First[endDate]-First[startDate])*12.+(endDate[[2]]-startDate[[2]]),3];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],quarter-=4];
If[cAddMonth[startDate,quarter*3]>end,quarter-=1];
lastQuarterList=cAddMonthList[startDate,quarter*3];
lastQuarter=AbsoluteTime[lastQuarterList];
nextQuarter=cAddMonth[lastQuarterList,3];
Return[quarter+(N[end]-lastQuarter)/(nextQuarter-lastQuarter)];
]
SetAttributes[yearDifference,Listable];
(* yearDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=-1*yearDifference[end,start] *)
yearDifference[start:_Integer|_Real,end:_Integer|_Real]/;start>end:=Block[{startDate=DateList[start],endDate=DateList[end],year,nextYear,lastYear,lastYearList},
year=First[endDate]-First[startDate];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],year+=1];
If[cAddYear[startDate,year]<end,year+=1];
lastYearList=cAddYearList[startDate,year];
lastYear=AbsoluteTime[lastYearList];
nextYear=cAddYear[lastYearList,-1];
Return[year-(N[end]-lastYear)/(nextYear-lastYear)];
]
yearDifference[start:_Integer|_Real,end:_Integer|_Real]:=Block[{startDate=DateList[start],endDate=DateList[end],year,nextYear,lastYear,lastYearList},
year=First[endDate]-First[startDate];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],year-=1];
If[cAddYear[startDate,year]>end,year-=1];
lastYearList=cAddYearList[startDate,year];
lastYear=AbsoluteTime[lastYearList];
nextYear=cAddYear[lastYearList,1];
Return[year+(N[end]-lastYear)/(nextYear-lastYear)];
]
End[];
(* ::Subsection:: *)
(*cDateDifference*)
cDateDifference::usage="Alternative to Mathematica built-in DateDifference.";
cDateDifference::invalidArgument="The argument \"`1`\" is not a valid `2`.";
SyntaxInformation[cDateDifference]={"ArgumentsPattern"->{_,_,_.}};
Begin["`Private`"];
(* convert units to numbers for sorting *)
cUnitValue[type_String|Quantity[_,type_]]:=Switch[type,
"Millennium"|"Millennia",1,
"Century"|"Centuries",2,
"Decade"|"Decades",3,
"Year"|"Years",4,
"Quarter"|"Quarters"|"QuarterYears",4.5,
"Month"|"Months",5,
"Week"|"Weeks",5.5,
"Day"|"Days",6,
"Hour"|"Hours",7,
"Minute"|"Minutes",8,
"Second"|"Seconds",9]
(* convert single/multiple units to Quantity units - raise a Message and Throw a Missing on invalid cases *)
cUnitToQuantityUnit[Quantity[1,type_]]:=type
cUnitToQuantityUnit[type_String]:=Switch[type,
"Second"|"Seconds","Seconds",
"Minute"|"Minutes","Minutes",
"Hour"|"Hours","Hours",
"Day"|"Days","Days",
"Week"|"Weeks","Weeks",
"Month"|"Months","Months",
"Quarter"|"Quarters"|"QuarterYears","QuarterYears",
"Year"|"Years","Years",
"Decade"|"Decades","Decades",
"Millennium"|"Millennia","Millennia",
"Century"|"Centuries","Centuries",
_,Message[cDateDifference::invalidArgument,type,"increment"];Throw[Missing["Increment"],1]]
(* reutrn start difference in float precision with it's corresponding unit as pair *)
cDateDifferenceCore[start:_Integer|_Real|{Repeated[_Integer|_Real]},end:_Integer|_Real|{Repeated[_Integer|_Real]},type_String|{type_String}|Quantity[1,type_]]:=Switch[type,
"Second"|"Seconds",{N[end]-start,"Seconds"},
"Minute"|"Minutes",{(end-start)/60.,"Minutes"},
"Hour"|"Hours",{(end-start)/3600.,"Hours"},
"Day"|"Days",{(end-start)/86400.,"Days"},
"Week"|"Weeks",{(end-start)/604800.,"Weeks"},
"Month"|"Months",{monthDifference[start,end],"Months"},
"Quarter"|"Quarters"|"QuarterYears",{quarterDifference[start,end],"QuarterYears"},
"Year"|"Years",{yearDifference[start,end],"Years"},
"Decade"|"Decades",{yearDifference[start,end]/10.,"Decades"},
"Century"|"Centuries",{yearDifference[start,end]/100.,"Centuries"},
"Millennium"|"Millennia",{yearDifference[start,end]/1000.,"Millennia"},
_,Message[cDateDifference::invalidArgument,type,"type"];Throw[Missing["Increment"],1];
]
(* multiple units *)
(* since we can't have duplicate signature, NumberQ was used *)
(* cDateDifferenceCore[start_?NumberQ,end_?NumberQ,types:{Repeated[_String|Quantity[1,_],{2,Infinity}]}]:=cDateDifferenceCore[start,end,DeleteDuplicates[cUnitToQuantityUnit/@types]] *)
cDateDifferenceCore[start:_Integer|_Real,end:_Integer|_Real,types:{Repeated[_String|Quantity[1,_],{2,Infinity}]}]:=Block[{sortedTypes=SortBy[types,cUnitValue],result},
result=Rest@FoldList[cDateDifferenceIntegerCore[Last@#1,#2]&,{{start,end}},Most[sortedTypes]];
{MixedMagnitude@#1,MixedUnit@#2}&@@Transpose@Append[Take[result,All,2],cDateDifferenceCore[result[[-1,3,1]],end,Last[sortedTypes]]]]
(* reutrn start difference in integer with it's corresponding unit as pair *)
(* used when multiple units is given to the cDateDifferenceCore *)
cDateDifferenceIntegerCore[{start:_Integer|_Real,end:_Integer|_Real},type_String|Quantity[1,type_]]:={#1[[1]],#2,{#1[[2]],end}}&@@Switch[type,
"Second"|"Seconds",{QuotientRemainder[end-start,1]*{1,-1}+{0,end},"Seconds"},
"Minute"|"Minutes",{QuotientRemainder[end-start,60]*{1,-1}+{0,end},"Minutes"},
"Hour"|"Hours",{QuotientRemainder[end-start,3600]*{1,-1}+{0,end},"Hours"},
"Day"|"Days",{QuotientRemainder[end-start,86400]*{1,-1}+{0,end},"Days"},
"Week"|"Weeks",{QuotientRemainder[end-start,604800]*{1,-1}+{0,end},"Weeks"},
"Month"|"Months",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=(First[endDate]-First[startDate])*12+(endDate[[2]]-startDate[[2]]);
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],result-=12;];
If[cAddMonth[startDate,result]>end,result-=1];
{result,AbsoluteTime[startDate+{0,result,0,0,0,0}]}],"Months"},
"Quarter"|"Quarters"|"QuarterYears",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=Quotient[(First[endDate]-First[startDate])*12+(endDate[[2]]-startDate[[2]]),3];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],result-=4;];
If[cAddMonth[startDate,result*3]>end,result-=1];
{result,AbsoluteTime[startDate+{0,result*3,0,0,0,0}]}],"QuarterYears"},
"Year"|"Years",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=First[endDate]-First[startDate];
(* Without Zero *)
If[Sign[First@startDate]!=Sign[First@endDate],result-=1;];
If[cAddYear[startDate,result]>end,result-=1];
{result,AbsoluteTime[startDate+{result,0,0,0,0,0}]}],"Years"},
"Decade"|"Decades",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=Quotient[First[endDate]-First[startDate],10];
If[cAddYear[startDate,10*result]>end,result-=1];
{result,AbsoluteTime[startDate+{10*result,0,0,0,0,0}]}],"Decades"},
"Century"|"Centuries",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=Quotient[First[endDate]-First[startDate],100];
If[cAddYear[startDate,100*result]>end,result-=1];
{result,AbsoluteTime[startDate+{100*result,0,0,0,0,0}]}],"Centuries"},
"Millennium"|"Millennia",{Block[{startDate=DateList[start],endDate=DateList[end],result},
result=Quotient[First[endDate]-First[startDate],1000];
If[cAddYear[startDate,1000*result]>end,result-=1];
{result,AbsoluteTime[startDate+{1000*result,0,0,0,0,0}]}],"Millennia"}
]
(* main form - receive start and end start as number *)
cDateDifference[start:_Integer|_Real,end:_Integer|_Real,Optional[type_String|Quantity[1,type_],"Day"]]:=Catch[Quantity@@cDateDifferenceCore[start,end,type],_,Defer@cDateDifference[start,end,type]&]
(* first/second argument needs conversion *)
cDateDifference[start:_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},end:_Integer|_Real,type:_String|_Quantity|{Repeated[_String|_Quantity]}:"Day"]:=Check[Quantity@@cDateDifferenceCore[AbsoluteTime[start],end,type],Defer@cDateDifference[start,end,type]]
cDateDifference[start:_Integer|_Real,end:_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},type:_String|_Quantity|{Repeated[_String|_Quantity]}:"Day"]:=Check[Quantity@@cDateDifferenceCore[start,AbsoluteTime[end],type],Defer@cDateDifference[start,end,type]]
cDateDifference[start:_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},end:_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},type:_String|_Quantity|{Repeated[_String|_Quantity]}:"Day"]:=Check[Quantity@@cDateDifferenceCore[AbsoluteTime@start,AbsoluteTime@end,type],Defer@cDateDifference[start,end,type]]
(* unit wrapped in a list *)
cDateDifference[start:_Integer|_Real,end:_Integer|_Real,type:{type_String|Quantity[1,type_]}]:=Check[Quantity@@cDateDifferenceCore[start,end,type],Defer@cDateDifference[start,end,type]]
(* multiple units *)
cDateDifference[start:_Integer|_Real,end:_Integer|_Real,types:{Repeated[_String|Quantity[1,_],{2,Infinity}]}]:=Catch[Quantity@@cDateDifferenceCore[start,end,DeleteDuplicates[cUnitToQuantityUnit/@types]],_,Defer@cDateDifference[start,end,types]&]
(* single,multiple *)
cDateDifference[start:_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},ends:{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},type:_String|_Quantity]:=Catch[Quantity@@@Thread@cDateDifferenceCore[AbsoluteTime@start,AbsoluteTime/@ends,type],_,Defer@cDateDifference[start,ends,type]&]
(* multiple, single *)
cDateDifference[starts:{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},end:_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},type:_String|_Quantity]:=Catch[Quantity@@@Thread@cDateDifferenceCore[AbsoluteTime/@starts,AbsoluteTime@end,type],_,Defer@cDateDifference[starts,end,type]&]
(* multiple, multiple *)
cDateDifference[starts:{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},ends:{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},type:_String|_Quantity]:=Catch[Quantity@@@Thread@cDateDifferenceCore[AbsoluteTime/@starts,AbsoluteTime/@ends,type],_,Defer@cDateDifference[starts,ends,type]&]
(* raise a Message for invalid arguments *)
cDateDifference[start:Except[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String]}],_,_]/;Message[cDateDifference::invalidArgument,start,"start start/list of start dates"]=False;
cDateDifference[_,end:Except[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String]}],_]/;Message[cDateDifference::invalidArgument,end,"end start/list of end dates"]=False;
cDateDifference[_,_,type:Except[_String|Quantity[1,_]|{Repeated[_String|Quantity[1,_]]}]]/;Message[cDateDifference::invalidArgument,type,"step/list of step"]=False;
End[];
(* ::Subsection:: *)
(*cDayNameIndex, cDayName*)
cDayName::usage="Alternative to Mathematica built-in DayName.";
cDayName::invalidArgument="The argument `1` is not a valid day/list of days.";
SyntaxInformation[cDayName]={"ArgumentsPattern"->{_}};
Begin["`Private`"];
(* return day index in the list of day names from first week of 1900 *)
cDayNameIndex[start:_Integer|_Real|{Repeated[_Integer|_Real]}]:=Mod[Quotient[start,86400],7]+1
(* return DayName , is Listable *)
cDayNameValue[start:_Integer|_Real|{Repeated[_Integer|_Real]}]:={Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}[[Mod[Quotient[start,86400],7]+1]]
(* single or list of dates *)
cDayName[start:_Integer|_Real|{Repeated[_Integer|_Real,{7,Infinity}]}]:=cDayNameValue[start]
(* start argument needs conversion *)
cDayName[start:_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]:=cDayNameValue@AbsoluteTime[start]
(* list of start needs conversion *)
cDayName[dates:{Repeated[{Repeated[_Integer|_Real,{1,6}]}|_DateObject|_String]}]:=cDayNameValue[AbsoluteTime/@dates]
(* raise Message for invalid arguments *)
cDayName[start:Except[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}|{Repeated[_Integer|_Real,{7,Infinity}]}|{Repeated[{Repeated[_Integer|_Real,{1,6}]}|_DateObject|_String]}]]/;Message[cDayName::invalidArgument,start,"start"]=False;
End[];
(* ::Subsection:: *)
(*cDatePlus*)
(* doesn not support real durations *)
cDatePlus::usage="Alternative to Mathematica built-in DatePlus.";
cDatePlus::invalidArgument="The argument `1` is not a valid argument for the `2`.";
SyntaxInformation[cDatePlus]={"ArgumentsPattern"->{_,_.}};
Begin["`Private`"];
(* convert Quantity to a pair *)
cQuantityToPair[Quantity[duration_,type:"Femtoseconds"|"Picoseconds"|"Nanoseconds"]]={0,"Second"};
cQuantityToPair[Quantity[duration_,type_]]:={duration,Switch[type,
"Millisecond"|"Milliseconds","Millisecond",
"Second"|"Seconds","Second",
"Minute"|"Minutes","Minute",
"Hour"|"Hours","Hour",
"Day"|"Days","Day",
"Week"|"Weeks","Week",
"Month"|"Months","Month",
"Quarter"|"Quarters"|"QuarterYears","Quarter",
"Year"|"Years","Year",
"Decade"|"Decades","Decade",
"Century"|"Centuries","Century",
"Millennium"|"Millennia","Millennium",
_,Message[cDatePlus::invalidArgument,type,"step"]
]}
(* convert units to a single base - used when multiple units is give to cDatePlus *)
cConvertUnit[{duration:_Integer|_Real,type:_String|_Symbol}|Quantity[duration_,type_]]:=Switch[type,
"Femtoseconds"|"Picoseconds"|"Nanoseconds",{0,"Second"},
"Millisecond"|"Milliseconds",{duration*10^-3,"Second"},
"Second"|"Seconds",{duration,"Second"},
"Minute"|"Minutes",{duration*60,"Second"},
"Hour"|"Hours",{duration*3600,"Second"},
"Day"|"Days",{duration*86400,"Second"},
"Week"|"Weeks",{duration*604800,"Second"},
"Month"|"Months",{duration,"Month"},
"Quarter"|"Quarters"|"QuarterYears",{duration*3,"Month"},
"Year"|"Years",{duration*12,"Month"},
"Decade"|"Decades",{120*duration,"Month"},
"Century"|"Centuries",{1200*duration,"Month"},
"Millennium"|"Millennia",{12000*duration,"Month"},
_,{duration,type}
]
(* merge sum-zero/zero units from list *)
cMergeUnits[units:{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=DeleteCases[Reverse@*List@@@Normal@GroupBy[cConvertUnit/@units,Last->First,Total],{0|0.,_},{1}]
(* used to show minimum precision in when ouputing DateList format *)
cCalculateDateLength[(type:_Integer|_Real|_Symbol|_String)|{_,type:_String|_Symbol}|Quantity[_,type_]]:=Switch[type,
"Hour"|"Hours",4,
"Minute"|"Minutes",5,
"Second"|"Seconds",6,
_,0
]
cCalculateDateLength[units:{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=Max[cCalculateDateLength/@units[[All,2]]]
(* used to find nth weekday/weekend day - used in cDatePlusNest *)
(* duration must be positive, the only call is with Abs[duration] - used in cDatePlusNest *)
cDatePlusNestCore[plainList_List,start_,1]:=start+86400*plainList[[cDayNameIndex[start]]]
cDatePlusNestCore[plainList_List,start_,duration_Integer]:=start+86400*Block[{offset=cDayNameIndex[start]},Nest[#+plainList[[Mod[#,7,1]]]&,offset,duration]-offset]
(* support negative list for nth weekday/weekend backward *)
cDatePlusNest[positiveList_List,negativeList_List,start_,duration_Integer]:=cDatePlusNestCore[If[Positive@duration,positiveList,negativeList],start,Abs[duration]]
(* find nth sunday/monday/... *)
cAddDayWithPattern[start_,1,pattPositive_List,pattNegative_List]:=start+86400.*pattPositive[[cDayNameIndex[start]]]
cAddDayWithPattern[start_,-1,pattPositive_List,pattNegative_List]:=start+86400.*pattNegative[[cDayNameIndex[start]]]
cAddDayWithPattern[start_,duration_,pattPositive_List,pattNegative_List]:=start+86400.*((duration-Sign[duration])*7.+If[Positive[duration],pattPositive,pattNegative][[cDayNameIndex[start]]])
(* zero duration reutrn the input *)
cDatePlusValue[start:_Integer|_Real|{Repeated[_Integer|_Real]},{0|.0,_String|_Symbol}]:=start
(* Map cDatePlusValue for units that are not Listable *)
cDatePlusValue[starts:{Repeated[_Integer|_Real]},step:{_,Except["Second"|"Minute"|"Hour"|"Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday]}]:=Thread[Unevaluated@cDatePlusValue[starts,step],List,{1}]
(* general function used for cDatePlus *)
cDatePlusValue[start:_Integer|_Real|{Repeated[_Integer|_Real]},{duration:_Integer|_Real,type:_String|_Symbol}]:=
Switch[type,
"Second"|"Seconds",start+duration,
"Minute"|"Minutes",start+60.*duration,
"Hour"|"Hours",start+3600.*duration,
"Day"|"Days",start+86400.*duration,
"Week"|"Weeks",start+604800.*duration,
Monday,cAddDayWithPattern[start,duration,{7,6,5,4,3,2,1},{-7,-1,-2,-3,-4,-5,-6}],
Tuesday,cAddDayWithPattern[start,duration,{1,7,6,5,4,3,2},{-6,-7,-1,-2,-3,-4,-5}],
Wednesday,cAddDayWithPattern[start,duration,{2,1,7,6,5,4,3},{-5,-6,-7,-1,-2,-3,-4}],
Thursday,cAddDayWithPattern[start,duration,{3,2,1,7,6,5,4},{-4,-5,-6,-7,-1,-2,-3}],
Friday,cAddDayWithPattern[start,duration,{4,3,2,1,7,6,5},{-3,-4,-5,-6,-7,-1,-2}],
Saturday,cAddDayWithPattern[start,duration,{5,4,3,2,1,7,6},{-2,-3,-4,-5,-6,-7,-1}],
Sunday,cAddDayWithPattern[start,duration,{6,5,4,3,2,1,7},{-1,-2,-3,-4,-5,-6,-7}],
"BusinessDay",Nest[Block[{temp=#+(If[Positive[duration],{1,1,1,1,3,2,1},{-3,-1,-1,-1,-1,-1,-2}][[cDayNameIndex[#]]])*86400},If[cHolidayQ[temp],cDatePlus[temp,{Sign[duration],"BusinessDay"}],temp]]&,start,Abs[duration]],
"Weekend"|"WeekendDay",cDatePlusNest[{5,4,3,2,1,1,6},{-1,-2,-3,-4,-5,-6,-1},start,duration],
"Weekday",cDatePlusNest[{1,1,1,1,3,2,1},{-3,-1,-1,-1,-1,-1,-2},start,duration],
(* unitStep are for negative durations *)
"BeginningOfMonth"|"MonthFirstDay",AbsoluteTime[DateList[start-UnitStep[-duration]*86400.]*{1,1,0,1,1,1}+{0,duration+UnitStep[-duration],1,0,0,0}],
"EndOfMonth"|"MonthLastDay",AbsoluteTime[DateList[Floor[start,86400.]+UnitStep[duration]*86400.]*{1,1,0,0,0,0}+{0,duration+UnitStep[-duration],0,0,0,0}]+Mod[start,86400.],
"Month"|"Months",cAddMonth[DateList[start],duration],
"Quarter"|"Quarters"|"QuarterYears",cAddMonth[DateList[start],duration*3],
"Year"|"Years",cAddYear[DateList[start],duration],
"Decade"|"Decades",cAddYear[DateList[start],duration*10],
"Century"|"Centuries",cAddYear[DateList[start],duration*100],
"Millennium"|"Millennia",cAddYear[DateList[start],duration*1000],
_,Message[cDatePlus::invalidArgument,type,"step"];Throw[Missing["step",type],1]]
(* cDatePlusValue with multiple units *)
cDatePlusValue[start:_Integer|_Real,steps:{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=Catch[Fold[cDatePlusValue[#1,#2]&,start,steps],_,Throw[Missing["step"],1]&]
cConvertResultFrom[result:_Integer|_Real,base:_Integer|_Real|_String|_DateObject|_TimeObject|{Repeated[_Integer|_Real,{1,6}]},step:{_Integer|_Real,_String|_Symbol}]:=Switch[Head[base],
Integer|Real,result,
List,DateListExtended[result,Max[Length[base],cCalculateDateLength[step]]],
DateObject,DateObject@DateListExtended[result,Max[Length[First@base],cCalculateDateLength[step]]],
TimeObject,TimeObject@Take[DateList@result,{4,Max[3+Length@First[base],cCalculateDateLength[step]]}],
String,DateString@result
]
(* raise error for multiple units sum to 0 - put above to make sure nothing wrong will go down *)
cDatePlus[start_,steps_]/;(cMergeUnits[steps]==={}):=(Message[cDatePlus::invalidArgument,steps,"step (does not increase or decrease the date)"];Defer[cDatePlus[start,steps]])
(* convert Quantity to pair *)
cDatePlus[start:_Integer|_Real|_String|_TimeObject|_DateObject|_DateInterval|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|_DateInterval|{Repeated[_Integer|_Real,{1,6}]}]},step_Quantity]:=Check[cDatePlus[start,cQuantityToPair@step],Defer@cDatePlus[start,step]]
(* no step is provided *)
cDatePlus[start:_Integer|_Real|_String|_TimeObject|_DateObject|_DateInterval|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|_DateInterval|{Repeated[_Integer|_Real,{1,6}]}]}]:=cDatePlus[start,{1,"Day"}]
(* single String|Symbol for second argument *)
cDatePlus[start:_Integer|_Real|_String|_TimeObject|_DateObject|_DateInterval|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|_DateInterval|{Repeated[_Integer|_Real,{1,6}]}]},type:_String|_Symbol|{Repeated[_String|_Symbol]}]:=Check[cDatePlus[start,Thread@{1,type}],Defer@cDatePlus[start,type]]
(* number for second argument *)
cDatePlus[start:_Integer|_Real|_DateObject|_String|_DateInterval|{Repeated[_Integer|_Real,{1,6}]},duration:_Integer|_Real]:=cDatePlus[start,{duration,"Day"}]
(* return start for empty list or zero Quantity for type *)
cDatePlus[start:_Integer|_Real|_String|_TimeObject|_DateObject|_DateInterval|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},{}|{0,_String|_Symbol}]:=start
(* convert output base on input type *)
cDatePlus[start:_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]},step:{_Integer|_Real,_String|_Symbol}|{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=Catch[Check[If[MatchQ[#,_Defer],#,Switch[Head[start],
Integer|Real,Identity[#],
List,DateListExtended[#,Max[Length[start],cCalculateDateLength[step]]],
DateObject,DateObject[DateListExtended[#,Max[Length[First@start],cCalculateDateLength[step]]]],
TimeObject,TimeObject@Take[DateList@#,{4,Max[3+Length@First[start],cCalculateDateLength[step]]}],
String,DateString[#]
]]&@cDatePlusValue[AbsoluteTime[start],step],Defer@cDatePlus[start,step]],_,Defer@cDatePlus[start,step]&]
(* cDatePlus for DateInterval *)
cDatePlus[date_DateInterval,step:{_Integer|_Real,_String|_Symbol}|{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=Check[DateInterval@Map[FromAbsoluteTime,Map[cDatePlus[AbsoluteTime@#,step]&,start["Dates"],{2}],{2}],Defer@cDatePlus[start,step]]
(* single/multiple item in first argument - interger/real seprated for saving performance because of applying AbsoluteTime *)
cDatePlus[starts:_Integer|_Real|{Repeated[_Integer|_Real,{7,Infinity}]},step:{_Integer|_Real,_String|_Symbol}]:=Catch[cDatePlusValue[starts,step],_,Defer@cDatePlus[starts,step]&]
cDatePlus[starts:{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},step:{_Integer|_Real,_String|_Symbol}|{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]:=Catch[With[{results=cDatePlusValue[AbsoluteTime/@starts,step]},Thread[Unevaluated@cConvertResultFrom[results,starts,step],List,2]],_,Defer@cDatePlus[starts,step]&]
(* raise Message for invalid arguments *)
cDatePlus[start:Except[_Integer|_Real|_String|_TimeObject|_DateObject|{Repeated[_Integer|_Real|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]}],_]/;Message[cDatePlus::invalidArgument,start,"start"]=False;
cDatePlus[_,step:Except[_Integer|_Real|_String|_Symbol|{_Integer|_Real,_String|_Symbol}|_Quantity|{Repeated[{_Integer|_Real,_String|_Symbol}|_Quantity]}]]/;Message[cDatePlus::invalidArgument,step,"step"]=False;
End[];
(* ::Subsection:: *)
(*cDayPlus*)
cDayPlus::usage="Alternative to Mathematica built-in DayPlus.";
cDayPlus::invalidArgument="The argument `1` is not a valid argument for the `2`.";
SyntaxInformation[cDayPlus]={"ArgumentsPattern"->{_,_,_.}};
Begin["`Private`"];
(* used cDatePlus as the engine *)
cDayPlus[start:_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},duration:_Integer|_Real,All]:=DateObject[cDatePlusValue[AbsoluteTime@start,{duration,"Day"}],"Day"]
cDayPlus[start:_Integer|_Real,duration:_Integer|_Real,type:"Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|"Week"|"Weekday"|"Weekend"|"EndOfMonth"|"BeginningOfMonth"|"BusinessDay":"Day"]:=DateObject[cDatePlusValue[start,{duration,type}],"Day"]
cDayPlus[start:_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},duration:_Integer|_Real,type:"Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|"Week"|"Weekday"|"Weekend"|"EndOfMonth"|"BeginningOfMonth"|"BusinessDay":"Day"]:=DateObject[cDatePlusValue[AbsoluteTime@start,{duration,type}],"Day"]
cDayPlus[dates:{Repeated[_Integer|_Real,{7,Infinity}]},duration:_Integer|_Real,type:"Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|"Week"|"Weekday"|"Weekend"|"EndOfMonth"|"BeginningOfMonth"|"BusinessDay":"Day"]:=DateObject[#,"Day"]&/@cDatePlusValue[dates,{duration,type}]
cDayPlus[dates:{Repeated[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},duration:_Integer|_Real,type:"Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|"Week"|"Weekday"|"Weekend"|"EndOfMonth"|"BeginningOfMonth"|"BusinessDay":"Day"]:=DateObject[#,"Day"]&/@cDatePlusValue[AbsoluteTime/@dates,{duration,type}]
(* raise Message for invalid arguments *)
cDayPlus[start:Except[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}|{Repeated[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]}],_,_]/;Message[cDayPlus::invalidArgument,start,"start"]=False;
cDayPlus[_,duration:Except[_Integer|_Real],_:"Day"]/;Message[cDayPlus::invalidArgument,duration,"duration"]=False;
cDayPlus[_,_,type:Except["Day"|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|"Week"|"Weekday"|"Weekend"|"EndOfMonth"|"BeginningOfMonth"|"BusinessDay"]]/;Message[cDayPlus::invalidArgument,type,"type"]=False;
End[];
(* ::Subsection:: *)
(*FromAbsoluteTimeExtended*)
Begin["`Private`"];
(* show DateList format without zero *)
(* with DateList applied, day/month could not be 0 *)
DateListExtended[start:_Real|_Integer|_DateObject|_TimeObject|_String|{Repeated[_Integer|_Real,{1,6}]}]:=Block[{temp=DateList[start]},Switch[temp,
{_,_,_,0,0,0.},Take[temp,3],
{_,_,_,_,0,0.},Take[temp,4],
{_,_,_,_,_,0.},Take[temp,5],
_,temp
]]
DateListExtended[start:_Real|_Integer|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},0]:=DateListExtended[start]
(* second argument is for allowing extra zeros to escape *)
DateListExtended[start:_Real|_Integer|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},upper_Integer]:=Block[{temp=DateList[start]},Switch[temp,
{_,_,_,0,0,0.},Take[temp,Max[3,upper]],
{_,_,_,_,0,0.},Take[temp,Max[4,upper]],
{_,_,_,_,_,0.},Take[temp,Max[5,upper]],
_,temp
]]
(* convert FromAbsolute to DateObject by removing extra zeros *)
FromAbsoluteTimeExtended[start:_Real|_Integer]:=DateObject@DateListExtended[start]
FromAbsoluteTimeExtended[start:_Real|_Integer,upper_Integer]:=DateObject@DateListExtended[start,upper]
FromAbsoluteTimeExtended[start:_Real|_Integer,0]:=DateObject@DateListExtended[start]
End[];
(* ::Subsection:: *)
(*cDayRound*)
cDayRound::usage="Alternative to Mathematica built-in DayRound.";
cDayRound::invalidArgument="The argument `1` is not a valid argument for the `2`.";
SyntaxInformation[cDayRound]={"ArgumentsPattern"->{_,_.}};
Begin["`Private`"];
(* Map cDayRoundValue for not listable types *)
cDayRoundValue[dates:{Repeated[_Integer|_Real]},type:"BusinessDay"|"EndOfMonth"|"MonthLastDay"|"BeginningOfMonth"|"MonthFirstDay"|"Holiday"]:=Catch[Thread[Unevaluated@cDayRoundValue[dates,type]],_,Throw[Missing["type"],1]&]
(* date argument is a number *)
cDayRoundValue[date:_Integer|_Real|{Repeated[_Integer|_Real]},type:_Symbol|_String]:=Block[{day=cDayNameIndex[date]},
Switch[type,
Sunday,7-day,
Monday,{0,6,5,4,3,2,1}[[day]],
Tuesday,{1,0,6,5,4,3,2}[[day]],
Wednesday,{2,1,0,6,5,4,3}[[day]],
Thursday,{3,2,1,0,6,5,4}[[day]],
Friday,{4,3,2,1,0,6,5}[[day]],
Saturday,{5,4,3,2,1,0,6}[[day]],
"Weekend"|"WeekendDay",{5,4,3,2,1,0,0}[[day]],
"Weekday",{0,0,0,0,0,2,1}[[day]],
"BusinessDay",Block[{offset={0,0,0,0,0,2,1}[[day]]},Block[{temp=date+offset*86400.},If[cHolidayQ[temp],offset+1+cDayRoundValue[temp+86400.,"BusinessDay"],offset]]],
"EndOfMonth"|"MonthLastDay",Quotient[AbsoluteTime[DateList[date]*{1,1,0,0,0,0}+{0,1,0,0,0,0}]-Floor[date,86400.],86400.],
"BeginningOfMonth"|"MonthFirstDay",Quotient[AbsoluteTime[DateList[date-86400.]*{1,1,0,0,0,0}+{0,1,1,0,0,0}]-Floor[date,86400.],86400.],
"Holiday",Quotient[cNextHoliday[date]-date,86400],
_,Message[cDayRound::invalidArgument,type,"type"];Throw[Missing["type"],1]
]]
(* return 0 for empty list as type *)
cDayRoundValue[_Integer|_Real,{}]:=0
(* return list of 0 for a list of dates with empty list as type *)
cDayRoundValue[date:{Repeated[_Integer|_Real]},{}]:=ConstantArray[0,Length[date]]
(* Map cDayRoundValue for not listable types *)
cDayRoundBackwardValue[dates:{Repeated[_Integer|_Real]},type:"BusinessDay"|"EndOfMonth"|"MonthLastDay"|"BeginningOfMonth"|"MonthFirstDay"|"Holiday"]:=Catch[Thread[Unevaluated@cDayRoundBackwardValue[dates,type]],_,Throw[Missing["type"],1]&]
(* date argument is a number *)
cDayRoundBackwardValue[date:_Integer|_Real|{Repeated[_Integer|_Real]},type:_Symbol|_String]:=Block[{day=cDayNameIndex[date]},
Switch[type,
Sunday,7-day,
Monday,{0,-1,-2,-3,-4,-5,-6}[[day]],
Tuesday,{-6,0,-1,-2,-3,-4,-5}[[day]],
Wednesday,{-5,-6,0,-1,-2,-3,-4}[[day]],
Thursday,{-4,-5,-6,0,-1,-2,-3}[[day]],
Friday,{-3,-4,-5,-6,0,-1,-2}[[day]],
Saturday,{-2,-3,-4,-5,-6,0,-1}[[day]],
"Weekend"|"WeekendDay",{-1,-2,-3,-4,-5,0,0}[[day]],
"Weekday",{0,0,0,0,0,-1,-2}[[day]],
"BusinessDay",Block[{offset={0,0,0,0,0,-1,-2}[[day]],temp},temp=date+offset*86400.;If[cHolidayQ[temp],offset+1+cDayRoundValue[temp+86400.,"BusinessDay"],offset]],
"EndOfMonth"|"MonthLastDay",Quotient[AbsoluteTime[DateList[date+86400.]*{1,1,0,0,0,0}]-Floor[date,86400.],86400.],
"BeginningOfMonth"|"MonthFirstDay",Quotient[AbsoluteTime[DateList[date]*{1,1,0,0,0,0}+{0,0,1,0,0,0}]-Floor[date,86400.],86400.],
"Holiday",Quotient[cPreviousHoliday[date]-date,86400],
_,Message[cDayRound::invalidArgument,type,"type"];Throw[Missing["type",1]]
]]
(* return 0 for empty list as type *)
cDayRoundBackwardValue[_Integer|_Real,{}]=0;
(* return list of 0 for a list of dates with empty list as type *)
cDayRoundBackwardValue[date:{Repeated[_Integer|_Real]},{}]:=ConstantArray[0,Length[date]]
(* do the calculations with cDayRoundValue *)
cDayRoundCore[date:_Integer|_Real,type:_Symbol|_String]:=DateObject[Floor[date,86400.]+cDayRoundValue[date,type]*86400.,"Day"]
(* do the calculations for a list of dates *)
cDayRoundCore[dates:{Repeated[_Integer|_Real]},type:_Symbol|_String]:=With[{calculatedDates=Floor[dates,86400.]+cDayRoundValue[dates,type]*86400.},Thread@Unevaluated@DateObject[calculatedDates,"Day"]]
(* single argument *)
(*cDayRound[date:_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]:=DateObject[date,"Day"]*)
(* list of dates without type *)
(*cDayRound[dates:{Repeated[_Integer|_Real,{7,Infinity}]}|{Repeated[_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]}]:=Thread[Unevaluated@DateObject[dates,"Day"]]*)
(* date argument is a number *)
cDayRound[date:_Integer|_Real,type:_Symbol|_String:"Day"]:=Catch[cDayRoundCore[date,type],_,Defer@cDayRound[date,type]&]
(* date argument needs conversion *)
cDayRound[date:_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},type:_Symbol|_String:"Day"]:=Catch[cDayRoundCore[AbsoluteTime@date,type],_,Defer@cDayRound[date,type]&]
(* list of dates that needs conversion with type *)
cDayRound[dates:{Repeated[_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]},type:_Symbol|_String:"Day"]:=Catch[cDayRoundCore[AbsoluteTime/@dates,type],_,Defer@cDayRound[dates,type]&]
(* list of numbers with type *)
cDayRound[dates:{Repeated[_Integer|_Real,{7,Infinity}]},type:_Symbol|_String:"Day"]:=Catch[cDayRoundCore[dates,type],_,Defer@cDayRound[dates,type]&]
(* raise Message for invalid arguments *)
cDayRound[date:Except[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]}],_]/;Message[cDayRound::invalidArgument,date,"date"]=False;
cDayRound[_,type:Except[_Symbol|_String]]/;Message[cDayRound::invalidArgument,type,"type"]=False;
End[];
(* ::Subsection:: *)
(*cHolidayQ*)
Begin["`Private`"];
cHolidayQ::invalidArgument="The input argument `1` is not a valid day.";
(* cAddDayOff is a function which will be applied to offical holidays to add "Day Off" days *)
cAddDayOff[_Integer][12,31,_Integer|_Real]={12,31,101.75};
cAddDayOff[year_Integer][1,1,holidayCode:_Integer|_Real]:=Switch[cDayNameIndex@AbsoluteTime@{year,1,1},7,{1,2,holidayCode+.25},_,{1,1,holidayCode}]
cAddDayOff[year_Integer][1,1,holidayCode:_Integer|_Real]:=Switch[cDayNameIndex@AbsoluteTime@{year,1,1},7,{1,2,holidayCode+.25},_,{1,1,holidayCode}]
cAddDayOff[year_Integer][month_Integer,day_Integer,holidayCode:_Integer|_Real]:=Switch[cDayNameIndex@AbsoluteTime@{year,month,day},6,{month,day-1,holidayCode+.75},7,{month,day+1,holidayCode+.25},_,{month,day,holidayCode}]
(* populate holidays for the give year and span of months *)
(* first if is a check to wether add YYYY-12-31 base one the YYYY+1-1-1 *)
cHolidayDaysGenerate[{year_,monthRange_Span}]:=cAddDayOff[year]@@@Catenate@*List@@HoldComplete[
{If[year>=1871,{1,1,101},Nothing],If[year>=1986,{1,{15,21,20,19,18,17,16}[[cDayNameIndex@AbsoluteTime@{year,1,1}]],102},Nothing]},
{If[1885<year<1971,{2,22,201},Nothing],If[year>=1971,{2,{15,21,20,19,18,17,16}[[cDayNameIndex@AbsoluteTime@{year,2,1}]],201},Nothing]},
Nothing,
Nothing,
{If[year>=1971,{5,{29,28,27,26,25,31,30}[[cDayNameIndex@AbsoluteTime@{year,5,1}]],501},Nothing]},
{If[year>=2021,{6,19,601},Nothing]},
{If[year>=1941,{7,4,701},Nothing]},
Nothing,
{If[year>=1894,{9,{1,7,6,5,4,3,2}[[cDayNameIndex@AbsoluteTime@{year,9,1}]],901},Nothing]},
{If[1977>=year>=1971,{10,{22,28,27,26,25,24,23}[[cDayNameIndex@AbsoluteTime@{year,10,1}]],1101},Nothing],If[1936<year<1971,{12,1001},Nothing],If[year>=1971,{10,{8,14,13,12,11,10,9}[[cDayNameIndex@AbsoluteTime@{year,10,1}]],1001},Nothing]},
{If[year>=1938&&Not[1977>=year>=1971],{11,11,1101},Nothing],If[year>=1863,{11,{25,24,23,22,28,27,26}[[cDayNameIndex@AbsoluteTime@{year,11,1}]],1102},Nothing]},
{If[year>=1871,{12,25,1201},Nothing],If[year>=1870&&cDayNameIndex@AbsoluteTime@{year+1,1,1}==6,{12,31,101.75},Nothing]}
][[monthRange]]
(* filter official holidays for a specific day or month or holidayCode *)
cHolidayDaysFilter[{year_Integer,month_Integer},holidayCode_Integer]:=Cases[cHolidayDaysGenerate[{year,month;;month}],{_,_,holidayCode},{1},1]
cHolidayDaysFilter[{year_Integer,month_Integer,day_Integer,Repeated[_,{0,3}]}]:=Cases[cHolidayDaysGenerate[{year,month;;month}],{_,day,_},{1},1]
(* convert official holiday pairs generated by cHolidayDays to AbsoluteTime values *)
cHolidayDaysToAbsolute[year_][result_List]:=AbsoluteTime[{year,##}]&@@@Take[result,All,2]
(* holidayQ without checking day offs *)
cHolidayQPlain[{year_Integer,month_Integer,day_Integer}]:=Switch[month,
3|4|8,False,
1,Or[year>=1871&&day==1,year>=1986&&day=={15,21,20,19,18,17,16}[[cDayNameIndex@AbsoluteTime@{year,1,1}]]],
2,Or[1885<year<1971&&day==22,year>=1971&&day=={15,21,20,19,18,17,16}[[cDayNameIndex@AbsoluteTime@{year,2,1}]]],
5,year>=1971&&day=={29,28,27,26,25,31,30}[[cDayNameIndex@AbsoluteTime@{year,5,1}]],
6,year>=2021&&day==19,
7,year>=1941&&day==4,
9,year>=1894&&day=={1,7,6,5,4,3,2}[[cDayNameIndex@AbsoluteTime@{year,9,1}]],
10,Or[1977>=year>=1971&&day=={22,28,27,26,25,24,23}[[cDayNameIndex@AbsoluteTime@{year,10,1}]],1936<year<1971&&day==12,year>=1971&&day=={8,14,13,12,11,10,9}[[cDayNameIndex@AbsoluteTime@{year,10,1}]]],
11,Or[year>=1938&&Not[1977>=year>=1971]&&day==11,year>=1863&&day=={25,24,23,22,28,27,26}[[cDayNameIndex@AbsoluteTime@{year,11,1}]]],
12,year>=1871&&day==25,
_,False
]
(* check wether a specific day is a holiday or not - for performance reason, code base has been duplicated *)
(* there is another method for checking holidays that uses cHolidayDays with slower performance *)
cHolidayQCore[{year_Integer,month_Integer,day_Integer}]:=
Or[cHolidayQPlain[{year,month,day}]&&cDayNameIndex[AbsoluteTime@{year,month,day}]<6,
(* is monday and sunday was a official holiday *)cDayNameIndex@AbsoluteTime@{year,month,day}==1&&cHolidayQPlain@Take[DateList@{year,month,day-1},3],
(* is friday and saturday is a official holiday *)cDayNameIndex@AbsoluteTime@{year,month,day}==5&&cHolidayQPlain@Take[DateList@{year,month,day+1},3]]
(* cHolidayYear will generate the official holidays base on the filters given *)
(* cHolidayYear[2020] *)
cHolidayYear[year_Integer]:=cHolidayDaysToAbsolute[year]@cHolidayDaysGenerate[{year,;;12}]
(* cHolidayYear[2020,2] - first 2 month *)
cHolidayYear[year_Integer,endMonth_Integer?Positive]:=cHolidayDaysToAbsolute[year]@cHolidayDaysGenerate[{year,1;;endMonth}]
(* cHolidayYear[2020,-2] - last 2 month *)
cHolidayYear[year_Integer,endMonth_Integer?Negative]:=cHolidayDaysToAbsolute[year]@cHolidayDaysGenerate[{year,endMonth;;12}]
(* cHolidayYear[2020,{2}] - only second month *)
cHolidayYear[year_Integer,{singleMonth_Integer}]:=cHolidayDaysToAbsolute[year]@cHolidayDaysGenerate[{year,singleMonth;;singleMonth}]
(* cHolidayYear[2020,{2,1}] - from 2020 to 2020-2-1 *)
cHolidayYear[year_Integer,{endMonth_Integer?Positive,endDay_Integer}]:=cHolidayDaysToAbsolute[year]@Join[If[endMonth!=1,cHolidayDaysGenerate[{year,1;;endMonth-1}],{}],Cases[cHolidayDaysGenerate[{year,endMonth;;endMonth}],{_,day_,_}/;day<=endDay]]
(* cHolidayYear[2020,{-2,1}] - from 2020-10-1 to 2021 *)
cHolidayYear[year_Integer,{startMonth_Integer?Negative,startDay_Integer}]:=cHolidayDaysToAbsolute[year]@Join[Cases[cHolidayDaysGenerate[{year,startMonth;;startMonth}],{_,day_,_}/;day>=startDay],If[startMonth!=-1,cHolidayDaysGenerate[{year,startMonth+1;;12}],{}]]
(* cHolidayYear[2020,{2,3},{4,5}] - from 2020-2-3 to 2020-4-5 *)
cHolidayYear[year_Integer,{startMonth_Integer?Positive,startDay_Integer},{endMonth_Integer?Positive,endDay_Integer}]/;startMonth<=endMonth:=Intersection[cHolidayYear[year,{startMonth-13,startDay}],cHolidayYear[year,{endMonth,endDay}]]
(* cHolidayYear[2020,{2,3},{2,5}] - from 2020-2-3 to 2020-2-5 *)
cHolidayYear[year_Integer,{month_Integer,startDay_Integer},{month_Integer,endDay_Integer}]/;startDay<endDay:=cHolidayDaysToAbsolute[year]@Cases[cHolidayDaysGenerate[{year,month;;month}],{_,Alternatives@@Range[startDay,endDay],_}]
cNextHoliday[date:_Integer|_Real|_DateObject|{Repeated[_Integer|_Real,{1,6}]}]:=Quiet[Check[First@cHolidayYear[#1,{#2,#3+1},{12,31}],cNextHoliday[{#1+1,1,1,0,0,0}]]&@@DateList[date]]
cPreviousHoliday::noOfficalHolidayExist="No offical holiday exists before 1863-11-26.";
cPreviousHoliday[date:_Integer|_Real|_DateObject|{Repeated[_Integer|_Real,{1,6}]}]:=Catch[If[AbsoluteTime[date]<-1139184000,Message[cPreviousHoliday::noOfficalHolidayExist];Throw["NoOfficalHolidayExist",1]];Quiet[Check[Last@If[#2==1&==1,cHolidayYear[#1-1,{1,1},{12,31}],cHolidayYear[#1,{1,1},{#2,#3-1}]],cPreviousHoliday[{#1-1,1,1,0,0,0}]]&@@DateList[date]],_,Defer@cPreviousHoliday[date]&]
(* generate official holidays for a range of start - used for cHolidayRange *)
cHolidayRangeCore[{startYear_Integer,startMonth_Integer,startDay_Integer},{endYear_Integer,endMonth_Integer,endDay_Integer}]:=Catenate@{
If[startYear==endYear,cHolidayYear[startYear,{startMonth,startDay},{endMonth,endDay}],cHolidayYear[startYear,{startMonth-13,startDay}]],
If[endYear-startYear>=2,Splice@*cHolidayYear/@Range[startYear+1,endYear-1],{}],
If[endYear>startYear,cHolidayYear[endYear,{endMonth,endDay}],{}]
}
(* return official holiday name + "Day off" days also included *)
(* if start is given, filter with cHolidayDays and use the return result to get the name *)
SyntaxInformation[cHolidayName]={"ArgumentsPattern"->{_}};
cHolidayName::invalidArgument="The input argument `1` is not a valid day.";
cHolidayName[start:_Integer|_Real|_String|_DateObject|{Repeated[_Integer|_Real,{1,6}]}]:=Block[{possibleDays=cHolidayDaysFilter[DateList@start]},If[Length@possibleDays==1,cHolidayNameCore@Take[First@possibleDays,{2,3}],Missing["Holiday"]]]
cHolidayName[start_]:=Message[cHolidayName::invalidArgument,start]
(* for real holidayCode (.25, .75) it's a "Day Off" holiday *)
cHolidayNameCore[{day_Integer,holidayCode_Real}]/;MatchQ[FractionalPart[holidayCode],.25|.75]:=If[MissingQ@#,#,#<>"'s day off"]&@cHolidayNameCore[{day,Floor[holidayCode]}]
(* for integer holidayCode, it's an offical holiday *)
cHolidayNameCore[{day_Integer,holidayCode_Integer}]:=Switch[holidayCode,
101,"New Year's Day",
102,"Martin Luther King Jr. Day",
201,"Presidents' Day",
501,"Memorial Day",
601,"Juneteenth",
701,"Independence Day",
901,"Labor Day",
1001,"Columbus Day",
1101,"Veterans Day",
1102,"Thanksgiving Day",
1201,"Christmas Day",
_,Throw[Missing["Holiday"],1]
]
(* generate official holidays for a range of start *)
cHolidayRange[start:_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]},end:_Integer|_Real|_DateObject|_String|{Repeated[_Integer|_Real,{1,6}]}]:=cHolidayRangeCore[Take[DateList[start],3],Take[DateList[end],3]]
(*
(* cHolidayQ - Method 1 - slower *)
cHolidayQ[a:_Integer|_Real|_String|{Repeated[_Integer|_Real,{1,6}]}]:=Length@cHolidayDays@DateList@a==1
cHolidayQ[a_DateObject]:=Length@cHolidayDays@Take[First[a],3]==1
*)
(* cHolidayQ - Method 2 uglier - almost 1.5 times faster than method 1 *)
cHolidayQ[date:_Integer|_Real|_String|_DateObject|{Repeated[_Integer|_Real,{1,6}]}]:=cHolidayQCore[Take[DateList[date],3]]
(* raise Message for dates without specific day *)
cHolidayQ[date:Except[_Integer|_Real|_String|_DateObject|{Repeated[_Integer|_Real,{1,6}]}]]:=(Message[cHolidayQ::invalidArgument,date];False)
End[];
(* ::Subsection:: *)
(*cDayRange*)
cDayRange::usage="Alternative to Mathematica built-in DayRange.";
cDayRange::invalidArgument="The argument `1` is not a valid argument for the `2`.";
SyntaxInformation[cDayRange]={"ArgumentsPattern"->{_,_,_.}};
Begin["`Private`"];
(* used to find every Sunday/Monday/Weekend/... *)
(* cCalculateDays[start:_Integer|_Real,days_Integer,target:{__Integer}]:=start+86400.*Sort@Catenate@Range[Mod[target-cDayNameIndex[start],7],days-1,7] *)
cCalculateDays[start:_Integer|_Real,days_Integer,target:{__Integer}]:=start+86400.*Sort@Catenate@Range[Mod[target-cDayNameIndex[start],7],days,7]
(* simplified with single target (sort is not needed) *)
(* cCalculateDays[start:_Integer|_Real,days_Integer,target_Integer]:=start+86400.*Range[Mod[target-cDayNameIndex[start],7],days-1,7] *)
cCalculateDays[start:_Integer|_Real,days_Integer,target_Integer]:=start+86400.*Range[Mod[target-cDayNameIndex[start],7],days,7]
(* used to find nth Sunday/Monday/Weekend/... *)
(* single target *)
(* cCalculateDays[start:_Integer|_Real,days_Integer,target_Integer,multiplier_Integer]:=start+86400.*Range[Mod[target-cDayNameIndex[start],Sign[multiplier]*7],Sign[multiplier]*days-Sign[multiplier],7*multiplier] *)
cCalculateDays[start:_Integer|_Real,days_Integer,target_Integer,multiplier_Integer]:=start+86400.*Range[Mod[target-cDayNameIndex[start],Sign[multiplier]*7],Sign[multiplier]*days,7*multiplier]
(* multiple target *)
cCalculateDays[start:_Integer|_Real,days_Integer,target:{__Integer},multiplier_Integer]:=start+86400.*Sort@Catenate@Range[Mod[target-cDayNameIndex[start],Sign[multiplier]*7],Sign[multiplier]*days+1,7*multiplier]
cMonthListWithDay[year_Integer,month_Integer]:=HoldComplete[31,28+First@cLeapYearValue[{year}],31,30,31,30,31,31,30,31,30,31][[month]]
(* return number of days for a given year *)
cMonthList[year_Integer]:={31,28+First@cLeapYearValue[{year}],31,30,31,30,31,31,30,31,30,31}
(* multiple year *)
cMonthList[years:{__Integer}]:={31,28+cLeapYearValue[years],31,30,31,30,31,31,30,31,30,31}
(* generate beginning of months between two start *)
cBeginningOfMonthRangeCore[removeLastMonth:True|False,{startYear_,startMonth_,startDay_,Repeated[0|0.,{0,3}]},{endYear_,endMonth_,_,Repeated[0|0.,{0,3}]},hms:Repeated[_Integer|_Real,{1,3}]:Nothing]:=AbsoluteTime/@Thread@{startYear,startMonth+Range[0+Boole[startDay!=1],(If[Sign@endYear!=Sign@startYear,endYear-1,endYear]-startYear)*12+endMonth-startMonth-Boole[removeLastMonth]],1,hms}
(* end could have extra item such as hour/minute/... *)
cBeginningOfMonthRange[{startYear_,startMonth_,startDay_},{endYear_,endMonth_,endDay_,Repeated[_Integer|_Real,{0,3}]}]:=cBeginningOfMonthRangeCore[False,{startYear,startMonth,startDay},{endYear,endMonth,endDay}]
(* start have extra item such as hour/minute/... *)
cBeginningOfMonthRange[{startYear_,startMonth_,startDay_,startHour_,startMinute_:0,startSecond_:0},{endYear_,endMonth_,endDay_}]:=cBeginningOfMonthRangeCore[endDay==1,{startYear,startMonth,startDay},{endYear,endMonth,endDay},startHour,startMinute,startSecond]
(* start and end have extra item such as hour/minute/... *)
cBeginningOfMonthRange[{startYear_,startMonth_,startDay_,startHour_,startMinute_:0,startSecond_:0},{endYear_,endMonth_,endDay_,endHour_,endMinute_:0,endSecond_:0},type_:All]:=cBeginningOfMonthRangeCore[If[endDay!=1,False,Dot[{startHour,startMinute,startSecond},{3600,60,1}]>Dot[{endHour,endMinute,endSecond},{3600,60,1}]],{startYear,startMonth,startDay},{endYear,endMonth,endDay},If[type==All,Unevaluated@Sequence[startHour,startMinute,startSecond],Nothing]]
(* generate end of months between two start *)
cEndOfMonthRangeCore[removeLastMonth:True|False,{startYear_,startMonth_,_,Repeated[0|0.,{0,3}]},{endYear_,endMonth_,endDay_,Repeated[0|0.,{0,3}]},hms:Repeated[_Integer|_Real,{0,3}]:Nothing]:=AbsoluteTime/@Thread@{startYear,startMonth+Range[1,(If[Sign@endYear!=Sign@startYear,endYear-1,endYear]-startYear)*12+endMonth-startMonth-Boole[removeLastMonth]+1],0,hms}
(* end could have extra item such as hour/minute/... *)
cEndOfMonthRange[{startYear_,startMonth_,startDay_},{endYear_,endMonth_,endDay_,Repeated[_Integer|_Real,{0,3}]}]:=cEndOfMonthRangeCore[endDay!=cMonthListWithDay[endYear,endMonth],{startYear,startMonth,startDay},{endYear,endMonth,endDay}]
(* start have extra item such as hour/minute/... *)
cEndOfMonthRange[{startYear_,startMonth_,startDay_,startHour_,startMinute_:0,startSecond_:0},{endYear_,endMonth_,endDay_}]:=cEndOfMonthRangeCore[endDay!=cMonthListWithDay[endYear,endMonth],{startYear,startMonth,startDay},{endYear,endMonth,endDay},startHour,startMinute,startSecond]
(* start and end have extra item such as hour/minute/... *)
cEndOfMonthRange[{startYear_,startMonth_,startDay_,startHour_,startMinute_:0,startSecond_:0},{endYear_,endMonth_,endDay_,endHour_,endMinute_:0,endSecond_:0},type_:All]:=cEndOfMonthRangeCore[If[endDay!=cMonthListWithDay[endYear,endMonth],True,Dot[{startHour,startMinute,startSecond},{3600,60,1}]>Dot[{endHour,endMinute,endSecond},{3600,60,1}]],{startYear,startMonth,startDay},{endYear,endMonth,endDay},If[type==All,Unevaluated@Sequence[startHour,startMinute,startSecond],Nothing]]
cDayRangeValue[start:_Integer|_Real,end:_Integer|_Real,type:_Symbol|_String]/;start>end:=Reverse@cDayRangeValue[end,start,type]
cDayRangeValue[start:_Integer|_Real,end:_Integer|_Real,type:_Symbol|_String]:=Block[{startDay=Floor[start,86400.],endDay=Ceiling[end,86400.],days},
(* days=Echo@Quotient[endDay-startDay,86400.]; *)
days=Quotient[Floor[end,86400.]-startDay,86400.];
Switch[type,
All|"Day",Range[startDay,endDay-86400.,86400.],