forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCFCalendar_Enumerate.c
2326 lines (2052 loc) · 142 KB
/
CFCalendar_Enumerate.c
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
/* CFCalendar_Enumerate.c
Copyright (c) 2004-2019, Apple Inc. and the Swift project authors
Portions Copyright (c) 2014-2019, Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
*/
#include "CFCalendar.h"
#include "CFCalendar_Internal.h"
#include "CFDateComponents.h"
#include "CFConstantKeys.h"
#include "CFInternal.h"
CF_PRIVATE CFDateRef _CFDateCreateWithTimeIntervalSinceDate(CFAllocatorRef allocator, CFTimeInterval ti, CFDateRef date) {
CFTimeInterval ti2 = CFDateGetAbsoluteTime(date);
return CFDateCreate(allocator, ti + ti2);
}
#pragma mark -
#define NUM_CALENDAR_UNITS (14)
static CFCalendarUnit const calendarUnits[NUM_CALENDAR_UNITS] = {kCFCalendarUnitEra, kCFCalendarUnitYear, kCFCalendarUnitQuarter, kCFCalendarUnitMonth, kCFCalendarUnitDay, kCFCalendarUnitHour, kCFCalendarUnitMinute, kCFCalendarUnitSecond, kCFCalendarUnitWeekday, kCFCalendarUnitWeekdayOrdinal, kCFCalendarUnitWeekOfMonth, kCFCalendarUnitWeekOfYear, kCFCalendarUnitYearForWeekOfYear, kCFCalendarUnitNanosecond};
static CFDateRef _CFCalendarCreateDateIfEraHasYear(CFCalendarRef calendar, CFIndex era, CFIndex year) {
CFDateComponentsRef tempComp = CFDateComponentsCreate(kCFAllocatorSystemDefault);
CFDateComponentsSetValue(tempComp, kCFCalendarUnitEra, era);
CFDateComponentsSetValue(tempComp, kCFCalendarUnitYear, year);
CFDateRef date = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, tempComp);
CFRelease(tempComp);
CFDateComponentsRef comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, date); // This is only needed for the comparison below
if (year == 1) {
CFDateComponentsRef addingUnit = CFDateComponentsCreate(kCFAllocatorSystemDefault);
CFDateComponentsSetValue(addingUnit, kCFCalendarUnitDay, 1);
// this is needed for Japanese calendar (and maybe other calenders with more than a few eras too)
while (CFDateComponentsGetValue(comp, kCFCalendarUnitEra) < era) {
CFDateRef newDate = _CFCalendarCreateDateByAddingDateComponentsToDate(kCFAllocatorSystemDefault, calendar, addingUnit, date, 0);
CFRelease(date);
date = newDate;
CFRelease(comp);
comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra, date);
}
CFRelease(addingUnit);
CFRelease(comp);
comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, date); // Because comp may have changed in the loop
}
CFIndex compEra = CFDateComponentsGetValue(comp, kCFCalendarUnitEra);
CFIndex compYear = CFDateComponentsGetValue(comp, kCFCalendarUnitYear);
CFRelease(comp);
if (compEra == era && compYear == year) { // For Gregorian calendar at least, era and year should always match up so date should always be assigned to result.
return date;
} else {
CFRelease(date);
}
return NULL;
}
static CFDateRef _CFCalendarCreateDateIfEraHasYearForWeekOfYear(CFCalendarRef calendar, CFIndex era, CFIndex yearForWeekOfYear, CFTimeInterval *resultInv) {
CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYear(calendar, era, yearForWeekOfYear);
if (yearBegin) {
// find the beginning of the year for week of year
CFDateRef result = NULL;
_CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitYearForWeekOfYear, &result, resultInv, yearBegin);
CFRelease(yearBegin);
return result;
}
return NULL;
}
static Boolean _CFCalendarCheckDateContainsMatchingComponents(CFCalendarRef calendar, CFDateRef date, CFDateComponentsRef compsToMatch, CFCalendarUnit *mismatchedUnits) {
Boolean dateMatchesComps = true;
CFCalendarRef cal = CFDateComponentsCopyCalendar(compsToMatch);
CFTimeZoneRef tz = CFDateComponentsCopyTimeZone(compsToMatch);
Boolean leapMonth = CFDateComponentsIsLeapMonth(compsToMatch);
Boolean isLeapMonthSet = CFDateComponentsIsLeapMonthSet(compsToMatch);
CFIndex era = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitEra);
CFIndex year = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYear);
CFIndex quarter = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitQuarter);
CFIndex month = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMonth);
CFIndex day = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitDay);
CFIndex hour = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitHour);
CFIndex minute = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMinute);
CFIndex second = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitSecond);
CFIndex weekday = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekday);
CFIndex weekdayordinal = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekdayOrdinal);
CFIndex weekOfMonth = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekOfMonth);
CFIndex weekOfYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekOfYear);
CFIndex yearForWeekOfYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYearForWeekOfYear);
CFIndex nanosecond = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitNanosecond);
CFIndex compsToMatchValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond};
CFCalendarUnit setUnits = 0;
for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) {
if (compsToMatchValues[i] != CFDateComponentUndefined) {
setUnits |= calendarUnits[i];
}
}
CFDateComponentsRef compsFromDate = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, setUnits, date);
if (cal) {
CFDateComponentsSetCalendar(compsFromDate, cal);
CFRelease(cal);
}
if (tz) {
CFDateComponentsSetTimeZone(compsFromDate, tz);
CFRelease(tz);
}
if (!CFEqual(compsFromDate, compsToMatch)) {
dateMatchesComps = false;
// Need to make them both arrays so we can cycle through them and find the mismatched units
CFIndex dateEra = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitEra);
CFIndex dateYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitYear);
CFIndex dateQuarter = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitQuarter);
CFIndex dateMonth = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitMonth);
CFIndex dateDay = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitDay);
CFIndex dateHour = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitHour);
CFIndex dateMinute = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitMinute);
CFIndex dateSecond = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitSecond);
CFIndex dateWeekday = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekday);
CFIndex dateWeekdayordinal = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekdayOrdinal);
CFIndex dateWeekOfMonth = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekOfMonth);
CFIndex dateWeekOfYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekOfYear);
CFIndex dateYearForWeekOfYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitYearForWeekOfYear);
CFIndex dateNanosecond = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitNanosecond);
CFIndex compsFromDateValues[NUM_CALENDAR_UNITS] = {dateEra, dateYear, dateQuarter, dateMonth, dateDay, dateHour, dateMinute, dateSecond, dateWeekday, dateWeekdayordinal, dateWeekOfMonth, dateWeekOfYear, dateYearForWeekOfYear, dateNanosecond};
if (mismatchedUnits) {
for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) {
if (compsToMatchValues[i] != compsFromDateValues[i]) {
*mismatchedUnits |= calendarUnits[i];
}
}
if (isLeapMonthSet) {
if (leapMonth != CFDateComponentsIsLeapMonth(compsFromDate)) {
*mismatchedUnits |= kCFCalendarUnitLeapMonth;
}
}
}
}
CFRelease(compsFromDate);
return dateMatchesComps;
}
static CFCalendarUnit _CFCalendarNextHigherUnit(CFCalendarUnit unit) {
CFCalendarUnit higherUnit = kCFNotFound;
switch (unit) {
case kCFCalendarUnitEra:
break;
case kCFCalendarUnitYear:
case kCFCalendarUnitYearForWeekOfYear:
higherUnit = kCFCalendarUnitEra;
break;
case kCFCalendarUnitWeekOfYear:
higherUnit = kCFCalendarUnitYearForWeekOfYear;
break;
case kCFCalendarUnitQuarter:
case kCFCalendarUnitLeapMonth:
case kCFCalendarUnitMonth:
higherUnit = kCFCalendarUnitYear;
break;
case kCFCalendarUnitDay:
case kCFCalendarUnitWeekOfMonth:
case kCFCalendarUnitWeekdayOrdinal:
higherUnit = kCFCalendarUnitMonth;
break;
case kCFCalendarUnitWeekday:
higherUnit = kCFCalendarUnitWeekOfMonth;
break;
case kCFCalendarUnitHour:
higherUnit = kCFCalendarUnitDay;
break;
case kCFCalendarUnitMinute:
higherUnit = kCFCalendarUnitHour;
break;
case kCFCalendarUnitSecond:
higherUnit = kCFCalendarUnitMinute;
break;
case kCFCalendarUnitNanosecond:
higherUnit = kCFCalendarUnitSecond;
default:
break;
}
return higherUnit;
}
static Boolean _CFCalendarCheckIfLeapMonthHack(CFCalendarRef calendar, CFDateRef date) {
// This is a hack. kCFCalendarUnitLeapMonth is SPI and components:fromDate: doesn't use it so we can't use it here (even though it's what we actually want), but whenever you create an NSDateComponents object, it sets leapMonthSet by default so we benefit.
// TODO: Fact check above statement
CFDateComponentsRef tempComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitMonth, date);
Boolean isLeapMonth = CFDateComponentsIsLeapMonth(tempComps);
Boolean isLeapMonthSet = CFDateComponentsIsLeapMonthSet(tempComps);
CFRelease(tempComps);
return (isLeapMonthSet && isLeapMonth);
}
static CFIndex _CFCalendarSetUnitCount(CFDateComponentsRef comps) {
CFIndex totalSetUnits = 0;
CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra);
CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear);
CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter);
CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth);
CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay);
CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour);
CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute);
CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond);
CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday);
CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal);
CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth);
CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear);
CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear);
CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond);
CFIndex compsValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond};
for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) {
if (compsValues[i] != CFDateComponentUndefined) totalSetUnits++;
}
return totalSetUnits;
}
#pragma mark -
#pragma mark Create Next Helpers
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingEra(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean *foundEra) {
const CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra);
if (era == CFDateComponentUndefined) return NULL;
CFIndex dateEra = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitEra, startDate);
if (era == dateEra) return NULL;
CFDateRef result = NULL;
if ((goBackwards && era <= dateEra) || (!goBackwards && era >= dateEra)) {
CFDateComponentsRef datecomp = CFDateComponentsCreate(kCFAllocatorSystemDefault);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitEra, era);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitYear, 1);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitMonth, 1);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitDay, 1);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitHour, 0);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitMinute, 0);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitSecond, 0);
CFDateComponentsSetValue(datecomp, kCFCalendarUnitNanosecond, 0);
result = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, datecomp);
CFRelease(datecomp);
CFIndex dateCompEra = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitEra, result);
if (dateCompEra != era) {
*foundEra = false; // cannot find the matching era
}
} else {
*foundEra = false; // cannot find the matching era
}
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear);
if (year == CFDateComponentUndefined) return NULL;
CFDateRef result = NULL;
CFDateComponentsRef dateComp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, startDate);
if (year != CFDateComponentsGetValue(dateComp, kCFCalendarUnitYear)) {
CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYear(calendar, CFDateComponentsGetValue(dateComp, kCFCalendarUnitEra), year);
if (yearBegin) {
// We set searchStartDate to the end of the year ONLY if we know we will be trying to match anything else beyond just the year and it'll be a backwards search; otherwise, we set searchStartDate to the start of the year.
const CFIndex totalSetUnits = _CFCalendarSetUnitCount(comps);
if (goBackwards && (totalSetUnits > 1)) {
CFTimeInterval yearEndInv = 0.0;
Boolean foundRange = CFCalendarGetTimeRangeOfUnit(calendar, kCFCalendarUnitYear, CFDateGetAbsoluteTime(yearBegin), NULL, &yearEndInv);
if (foundRange) {
result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearEndInv-1, yearBegin);
}
CFRelease(yearBegin);
} else {
result = yearBegin;
}
}
}
CFRelease(dateComp);
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingYearForWeekOfYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear);
if (yearForWeekOfYear == CFDateComponentUndefined) return NULL;
CFDateRef result = NULL;
CFDateComponentsRef dateComp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYearForWeekOfYear, startDate);
if (yearForWeekOfYear != CFDateComponentsGetValue(dateComp, kCFCalendarUnitYearForWeekOfYear)) {
CFTimeInterval yearInv = 0.0;
CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYearForWeekOfYear(calendar, CFDateComponentsGetValue(dateComp, kCFCalendarUnitEra), yearForWeekOfYear, &yearInv);
if (yearBegin) {
if (goBackwards) {
// We need to set searchStartDate to the end of the year
CFTimeInterval yearEndInv = 0.0;
Boolean foundRange = CFCalendarGetTimeRangeOfUnit(calendar, kCFCalendarUnitYearForWeekOfYear, CFDateGetAbsoluteTime(yearBegin), NULL, &yearEndInv);
if (foundRange) {
result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearEndInv-1, yearBegin);
}
CFRelease(yearBegin);
} else {
result = yearBegin;
}
}
}
CFRelease(dateComp);
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingQuarter(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter);
if (quarter == CFDateComponentUndefined) return NULL;
CFDateRef result = NULL;
// So this is a thing -- <rdar://problem/30229506> NSCalendar -component:fromDate: always returns 0 for kCFCalendarUnitQuarter
CFDateRef yearBegin = NULL;
CFTimeInterval yearInv = 0.0;
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitYear, &yearBegin, &yearInv, startDate); // Get the beginning of the year we need
if (foundRange) {
CFIndex count;
CFDateRef quarterBegin = NULL;
CFTimeInterval quarterInv = 0.0;
if (goBackwards) {
quarterBegin = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearInv-1, yearBegin);
CFRelease(yearBegin);
count = 4;
while ((count != quarter) && (count > 0)) {
CFDateRef tempDate = NULL;
foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitQuarter, &tempDate, &quarterInv, quarterBegin);
CFRelease(quarterBegin);
quarterBegin = tempDate;
quarterInv *= -1;
tempDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, quarterInv, quarterBegin);
CFRelease(quarterBegin);
quarterBegin = tempDate;
count--;
}
} else {
count = 1;
quarterBegin = yearBegin;
while ((count != quarter) && (count < 5)) {
CFDateRef tempDate = NULL;
foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitQuarter, &tempDate, &quarterInv, quarterBegin);
CFRelease(quarterBegin);
quarterBegin = tempDate;
tempDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, quarterInv, quarterBegin);
CFRelease(quarterBegin);
quarterBegin = tempDate;
count++;
}
}
result = quarterBegin;
}
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekOfYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear);
if (weekOfYear == CFDateComponentUndefined) return NULL;
CFIndex dateWeekOfYear = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfYear, startDate);
if (weekOfYear == dateWeekOfYear) {
// Already matches
return NULL;
}
// After this point, the result is at least the start date
CFDateRef result = CFRetain(startDate);
CFDateRef woyBegin = NULL;
CFTimeInterval woyInv = 0.0;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfYear, &woyBegin, &woyInv, result);
if (foundRange) {
if (goBackwards) {
// If yearForWeekOfYear is set, at this point we'd already be at the end of the right year, so we can just iterate backward to find the week we need
woyInv *= -1; // So we can go backwards in time
}
CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, woyInv, woyBegin);
dateWeekOfYear = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfYear, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
CFRelease(woyBegin);
}
} while (weekOfYear != dateWeekOfYear);
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingMonth(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean isStrictMatching) {
const CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth);
if (month == CFDateComponentUndefined) return NULL;
Boolean isLeapMonthDesired = CFDateComponentsIsLeapMonth(comps);
Boolean isLeapMonthSetDesired = CFDateComponentsIsLeapMonthSet(comps);
const Boolean isChineseCalendar = CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierChinese);
// isLeapMonth only works for Chinese calendar
if (!isChineseCalendar) {
isLeapMonthSetDesired = false;
isLeapMonthDesired = false;
}
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
CFIndex dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, result);
if (month != dateMonth) {
CFDateRef monthBegin = NULL;
CFTimeInterval mInv = 0.0;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &monthBegin, &mInv, result);
if (foundRange) {
// If year is set, at this point we'd already be at the start of the right year, so we can just iterate forward to find the month we need
if (goBackwards) {
CFIndex numMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, monthBegin);
if ((numMonth == 3) && CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierGregorian)) {
mInv -= (86400*3); // Take it back 3 days so we land in february. That is, March has 31 days, and Feb can have 28 or 29, so to ensure we get to either Feb 1 or 2, we need to take it back 3 days.
} else {
mInv -= 86400; // Take it back a day
}
mInv *= -1; // So we can go backwards in time
}
CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, mInv, monthBegin);
dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
CFRelease(monthBegin);
}
} while (month != dateMonth);
}
// As far as we know, this is only relevant for the Chinese calendar. In that calendar, the leap month has the same month number as the preceding month.
// If we're searching forwards in time looking for a leap month, we need to skip the first occurrence we found of that month number because the first occurrence would not be the leap month; however, we only do this is if we are matching strictly. If we don't care about strict matching, we can skip this and let the caller handle it so it can deal with the approximations if necessary.
if (isLeapMonthSetDesired && isLeapMonthDesired && isStrictMatching) {
CFDateRef leapMonthBegin = NULL;
CFTimeInterval leapMonthInv = 0.0;
Boolean leapMonthFound = false;
// We should check if we're already at a leap month!
if (!_CFCalendarCheckIfLeapMonthHack(calendar, result)) {
CFDateRef tempSearchDate = CFRetain(result);
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &leapMonthBegin, &leapMonthInv, tempSearchDate);
if (foundRange) {
if (goBackwards) {
if (isChineseCalendar) {
// Months in the Chinese calendar can be either 29 days ("short month") or 30 days ("long month"). We need to account for this when moving backwards in time so we don't end up accidentally skipping months. If leapMonthBegin is 30 days long, we need to subtract from that 30 so we don't potentially skip over the previous short month.
// Also note that some days aren't exactly 24hrs long, so we can end up with lengthOfMonth being something like 29.958333333332, for example. This is a (albeit hacky) way of getting around that.
double lengthOfMonth = leapMonthInv / 86400;
if (lengthOfMonth > 30) {
leapMonthInv -= 86400*2;
} else if (lengthOfMonth > 28) {
leapMonthInv -= 86400;
}
}
leapMonthInv *= -1;
}
CFDateRef tempPossibleLeapMonth = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, leapMonthInv, leapMonthBegin);
CFDateComponentsRef monthComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitMonth|kCFCalendarUnitLeapMonth, tempPossibleLeapMonth);
dateMonth = CFDateComponentsGetValue(monthComps, kCFCalendarUnitMonth);
Boolean tempLeapMonth = false;
if (CFDateComponentsIsLeapMonthSet(monthComps)) {
tempLeapMonth = CFDateComponentsIsLeapMonth(monthComps);
}
CFRelease(monthComps);
if ((dateMonth == month) && tempLeapMonth) {
CFRelease(result);
result = tempPossibleLeapMonth;
leapMonthFound = true;
} else {
CFRelease(tempSearchDate);
tempSearchDate = tempPossibleLeapMonth;
}
CFRelease(leapMonthBegin);
}
} while (!leapMonthFound);
CFRelease(tempSearchDate);
}
}
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekOfMonth(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth);
if (weekOfMonth == CFDateComponentUndefined) return NULL;
CFIndex dateWeekOfMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfMonth, startDate);
if (weekOfMonth == dateWeekOfMonth) {
// Already matches
return NULL;
}
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
CFDateRef womBegin = NULL;
CFTimeInterval womInv = 0.0;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &womBegin, &womInv, result);
if (foundRange) {
// We need to advance or rewind to the next week.
// This is simple when we can jump by a whole week interval, but there are complications around WoM == 1 because it can start on any day of the week. Jumping forward/backward by a whole week can miss it.
//
// A week 1 which starts on any day but Sunday contains days from week 5 of the previous month, e.g.
//
// June 2018
// Su Mo Tu We Th Fr Sa
// 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
//
// Week 1 of June 2018 starts on Friday; any day before that is week 5 of May.
// We can jump by a week interval if we're not looking for WoM == 2 or we're not close.
bool advanceDaily = (weekOfMonth == 1) /* we're looking for WoM == 1 */;
if (goBackwards) {
// Last week/earlier this week is week 1.
advanceDaily &= dateWeekOfMonth <= 2;
} else {
// We need to be careful if it's the last week of the month. We can't assume what number week that would be, so figure it out.
CFRange range = CFCalendarGetRangeOfUnit(calendar, kCFCalendarUnitWeekOfMonth, kCFCalendarUnitMonth, CFDateGetAbsoluteTime(result));
advanceDaily &= dateWeekOfMonth == range.length;
}
CFDateRef tempSearchDate = NULL;
if (!advanceDaily) {
// We can jump directly to next/last week. There's just one further wrinkle here when doing so backwards: due to DST, it's possible that this week is longer/shorter than last week.
// That means that if we rewind by womInv (the length of this week), we could completely skip last week, or end up not at its first instant.
//
// We can avoid this by not rewinding by womInv, but by going directly to the start.
if (goBackwards) {
// Any instant before womBegin is last week.
CFDateRef lateLastWeek = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, womBegin);
if (!_CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &tempSearchDate, NULL, lateLastWeek)) {
// It shouldn't be possible to hit this case, but if we somehow got here, we can fall back to searching day by day.
advanceDaily = YES;
}
CFRelease(lateLastWeek);
} else {
// Skipping forward doesn't have these DST concerns, since womInv already represents the length of this week.
tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, womInv, womBegin);
}
}
// This is a separate condition because it represents a "possible" fallthrough from above.
if (advanceDaily) {
// The start of week 1 of any month is just day 1 of the month.
CFDateRef today = CFRetain(womBegin);
while (CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, today) != 1) {
CFDateRef next = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, (goBackwards ? -1 : 1), kCFCalendarUnitDay, today);
CFRelease(today);
today = next;
}
tempSearchDate = today;
}
CFRelease(womBegin);
dateWeekOfMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfMonth, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
}
} while (weekOfMonth != dateWeekOfMonth);
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekdayOrdinal(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal);
if (weekdayordinal == CFDateComponentUndefined) return NULL;
CFIndex dateWeekdayOrd = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekdayOrdinal, startDate);
if (weekdayordinal == dateWeekdayOrd) {
// Already matches
return NULL;
}
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
CFDateRef wdBegin = NULL;
CFTimeInterval wdInv = 0.0;
do {
// TODO: Consider jumping ahead by week here instead of day.
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekdayOrdinal, &wdBegin, &wdInv, result);
if (foundRange) {
if (goBackwards) {
wdInv *= -1; // So we can go backwards in time
}
CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, wdInv, wdBegin);
CFRelease(wdBegin);
dateWeekdayOrd = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekdayOrdinal, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
}
} while (weekdayordinal != dateWeekdayOrd);
// NOTE: In order for an ordinal weekday to not be ambiguous, it needs both
// - the ordinality (e.g. 1st)
// - the weekday (e.g. Tuesday)
// If the weekday is not set, we assume the client just wants the first time in a month where the number of occurrences of a day matches the weekdayOrdinal value (e.g. for weekdayOrdinal = 4, this means the first time a weekday is the 4th of that month. So if the start date is 2017-06-01, then the first time we hit a day that is the 4th occurrence of a weekday would be 2017-06-22. I recommend looking at the month in its entirety on a calendar to see what I'm talking about.). This is an odd request, but we will return that result to the client while silently judging them.
// For a non-ambiguous ordinal weekday (i.e. the ordinality and the weekday have both been set), we need to ensure that we get the exact ordinal day that we are looking for. Hence the below weekday check.
const CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday);
if (weekday == CFDateComponentUndefined) {
// Skip weekday
return result;
}
// Once we're here, it means we found a day with the correct ordinality, but it may not be the specific weekday we're also looking for (e.g. we found the 2nd Thursday of the month when we're looking for the 2nd Friday).
CFIndex dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, result);
if (weekday == dateWeekday) {
// Already matches
return result;
}
// Start result over
CFRelease(result);
result = NULL;
if (dateWeekday > weekday) {
// We're past the weekday we want. Go to the beginning of the week
// We use startDate again here, not result
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &result, NULL, startDate);
if (foundRange) {
CFDateComponentsRef startingDayWeekdayComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitWeekday|kCFCalendarUnitWeekdayOrdinal, result);
dateWeekday = CFDateComponentsGetValue(startingDayWeekdayComps, kCFCalendarUnitWeekday);
dateWeekdayOrd = CFDateComponentsGetValue(startingDayWeekdayComps, kCFCalendarUnitWeekdayOrdinal);
CFRelease(startingDayWeekdayComps);
}
}
if (!result) {
// We need to have a value here - use the start date
result = CFRetain(startDate);
}
while ((weekday != dateWeekday) || (weekdayordinal != dateWeekdayOrd)) {
// Now iterate through each day of the week until we find the specific weekday we're looking for.
CFDateRef currWeekday = NULL;
CFTimeInterval currWeekdayInv = 0.0;
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &currWeekday, &currWeekdayInv, result);
if (foundRange) {
CFDateRef nextDay = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, currWeekdayInv, currWeekday);
CFDateComponentsRef nextDayWeekdayComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitWeekday|kCFCalendarUnitWeekdayOrdinal, nextDay);
dateWeekday = CFDateComponentsGetValue(nextDayWeekdayComps, kCFCalendarUnitWeekday);
dateWeekdayOrd = CFDateComponentsGetValue(nextDayWeekdayComps, kCFCalendarUnitWeekdayOrdinal);
CFRelease(nextDayWeekdayComps);
CFRelease(result);
result = nextDay;
CFRelease(currWeekday);
}
}
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekday(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) {
// NOTE: This differs from the weekday check in weekdayOrdinal because weekday is meant to be ambiguous and can be set without setting the ordinality.
// e.g. inquiries like "find the next tuesday after 2017-06-01" or "find every wednesday before 2012-12-25"
const CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday);
if (weekday == CFDateComponentUndefined) return NULL;
CFIndex dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, startDate);
if (weekday == dateWeekday) {
// Already matches
return NULL;
}
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
CFDateRef wdBegin = NULL;
CFTimeInterval wdInv = 0.0;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekday, &wdBegin, &wdInv, result);
if (foundRange) {
// We need to either advance or rewind by a day.
// * Advancing to tomorrow is relatively simple: get the start of today and get the length of that day — then, advance by that length
// * Rewinding to the start of yesterday is more complicated: the length of today is not necessarily the length of yesterday if DST transitions are involved:
// * Today can have 25 hours: if we rewind 25 hours from the start of today, we'll skip yesterday altogether
// * Today can have 24 hours: if we rewind 24 hours from the start of today, we might skip yesterday if it had 23 hours, or end up at the wrong time if it had 25
// * Today can have 23 hours: if we rewind 23 hours from the start of today, we'll end up at the wrong time yesterday
//
// We need to account for DST by ensuring we rewind to exactly the time we want.
CFDateRef tempSearchDate = NULL;
if (goBackwards) {
// Any time prior to dayBegin is yesterday. Since we want to rewind to the start of yesterday, do that directly.
CFDateRef lateYesterday = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, wdBegin);
CFDateRef yesterdayBegin = NULL;
// Now we can get the exact moment that yesterday began on.
// It shouldn't be possible to fail to find this interval, but if that somehow happens, we can try to fall back to the simple but wrong method.
foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &yesterdayBegin, NULL, lateYesterday);
if (foundRange) {
tempSearchDate = yesterdayBegin;
} else {
// This fallback is only really correct when today and yesterday have the same length.
// Again, it shouldn't be possible to hit this case.
tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -wdInv, wdBegin);
}
CFRelease(lateYesterday);
} else {
// This is always correct to do since we are using today's length on today — there can't be a mismatch.
tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, wdInv, wdBegin);
}
CFRelease(wdBegin);
dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
}
} while (weekday != dateWeekday);
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingDay(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards) {
const CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay);
if (day == CFDateComponentUndefined) return NULL;
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
CFIndex dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, result);
const CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth);
if ((month != CFDateComponentUndefined) && goBackwards) {
// Are we in the right month already? If we are and goBackwards is set, we should move to the beginning of the last day of the month and work backwards.
CFDateRef monthBegin = NULL;
CFTimeInterval monthInv = 0.0;
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &monthBegin, &monthInv, result);
if (foundRange) {
CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, monthInv-1, monthBegin);
// Check the order to make sure we didn't jump ahead of the start date
CFComparisonResult order = CFDateCompare(tempSearchDate, originalStartDate, NULL);
if (order == kCFCompareGreaterThan) {
// We went too far ahead. Just go back to using the start date as our upper bound.
CFRelease(result);
result = CFRetain(originalStartDate);
} else {
CFDateRef dayBegin = NULL;
CFTimeInterval dInv = 0.0;
foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, tempSearchDate);
if (foundRange) {
CFRelease(result);
result = dayBegin;
dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, result);
}
}
CFRelease(tempSearchDate);
CFRelease(monthBegin);
}
}
CFDateRef dayBegin = NULL;
CFTimeInterval dInv = 0.0;
if (day != dateDay) {
// The condition below keeps us from blowing past a month day by day to find a day which does not exist.
// e.g. trying to find the 30th of February starting in January would go to March 30th if we don't stop here
CFIndex const originalMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, result);
Boolean advancedPastWholeMonth = false;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, result);
if (foundRange) {
// We need to either advance or rewind by a day.
// * Advancing to tomorrow is relatively simple: get the start of today and get the length of that day — then, advance by that length
// * Rewinding to the start of yesterday is more complicated: the length of today is not necessarily the length of yesterday if DST transitions are involved:
// * Today can have 25 hours: if we rewind 25 hours from the start of today, we'll skip yesterday altogether
// * Today can have 24 hours: if we rewind 24 hours from the start of today, we might skip yesterday if it had 23 hours, or end up at the wrong time if it had 25
// * Today can have 23 hours: if we rewind 23 hours from the start of today, we'll end up at the wrong time yesterday
//
// We need to account for DST by ensuring we rewind to exactly the time we want.
CFDateRef tempSearchDate = NULL;
if (goBackwards) {
// Any time prior to dayBegin is yesterday. Since we want to rewind to the start of yesterday, do that directly.
CFDateRef lateYesterday = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, dayBegin);
CFDateRef yesterdayBegin = NULL;
// Now we can get the exact moment that yesterday began on.
// It shouldn't be possible to fail to find this interval, but if that somehow happens, we can try to fall back to the simple but wrong method.
foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &yesterdayBegin, NULL, lateYesterday);
if (foundRange) {
tempSearchDate = yesterdayBegin;
} else {
// This fallback is only really correct when today and yesterday have the same length.
// Again, it shouldn't be possible to hit this case.
tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -dInv, dayBegin);
}
CFRelease(lateYesterday);
} else {
// This is always correct to do since we are using today's length on today -- there can't be a mismatch.
tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, dInv, dayBegin);
}
CFRelease(dayBegin);
dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, tempSearchDate);
CFIndex const dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, tempSearchDate);
CFRelease(result);
result = tempSearchDate;
if (llabs(dateMonth - originalMonth) >= 2) {
advancedPastWholeMonth = true;
break;
}
}
} while (day != dateDay);
// If we blew past a month in its entirety, roll back by a day to the very end of the month.
if (advancedPastWholeMonth) {
CFDateRef const tempSearchDate = result;
result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -dInv, tempSearchDate);
CFRelease(tempSearchDate);
}
} else {
// When the search date matches the day we're looking for, we still need to clear the lower components in case they are not part of the components we're looking for.
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, result);
if (foundRange) {
CFRelease(result);
result = dayBegin;
}
}
return result;
}
static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingHour(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean findLastMatch, Boolean isStrictMatching, CFOptionFlags options) {
const CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour);
if (hour == CFDateComponentUndefined) return NULL;
// After this point, result is at least startDate
CFDateRef result = CFRetain(startDate);
Boolean adjustedSearchStartDate = false;
CFIndex dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, result);
// The loop below here takes care of advancing forward in the case of an hour mismatch, taking DST into account.
// However, it does not take into account a unique circumstance: searching for hour 0 of a day on a day that has no hour 0 due to DST.
//
// America/Sao_Paulo, for instance, is a time zone which has DST at midnight -- an instant after 11:59:59 PM can become 1:00 AM, which is the start of the new day:
//
// 2018-11-03 2018-11-04
// ┌─────11:00 PM (GMT-3)─────┐ │ ┌ ─ ─ 12:00 AM (GMT-3)─ ─ ─┐ ┌─────1:00 AM (GMT-2) ─────┐
// │ │ │ | │ │ │
// └──────────────────────────┘ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ └▲─────────────────────────┘
// Nonexistent └── Start of Day
//
// The issue with this specifically is that parts of the rewinding algorithm that handle overshooting rewind to the start of the day to search again (or alternatively, adjusting higher components tends to send us to the start of the day).
// This doesn't work when the day starts past the time we're looking for if we're looking for hour 0.
//
// If we're not matching strictly, we need to check whether we're already a non-strict match and not an overshoot.
if (hour == 0 /* searching for hour 0 */ && !isStrictMatching) {
CFDateRef dayBegin = NULL;
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, NULL, result);
if (foundRange) {
CFIndex firstHourOfTheDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, dayBegin);
if (firstHourOfTheDay != 0 && dateHour == firstHourOfTheDay) {
// We're at the start of the day; it's just not hour 0.
// We have a candidate match. We can modify that match based on the actual options we need to set.
if (options & kCFCalendarMatchNextTime) {
// We don't need to preserve the smallest components. We can wipe them out.
// Note that we rewind to the start of the hour by rewinding to the start of the day -- normally we'd want to rewind to the start of _this_ hour in case there were a difference in a first/last scenario (repeated hour DST transition), but we can't both be missing hour 0 _and_ be the second hour in a repeated transition.
result = CFRetain(dayBegin);
} else if (options & kCFCalendarMatchNextTimePreservingSmallerUnits || options & kCFCalendarMatchPreviousTimePreservingSmallerUnits) {
// We want to preserve any currently set smaller units (hour and minute), so don't do anything.
// If we need to match the previous time (i.e. go back an hour), that adjustment will be made elsewhere, in the generalized isForwardDST adjustment in the main loop.
}
// Avoid making any further adjustments again.
adjustedSearchStartDate = YES;
}
CFRelease(dayBegin);
}
}
// This is a real mismatch and not due to hour 0 being missing.
// NOTE: The behavior of generalized isForwardDST checking depends on the behavior of this loop!
// Right now, in the general case, this loop stops iteration _before_ a forward DST transition. If that changes, please take a look at the isForwardDST code for when `beforeTransition = NO` and adjust as necessary.
if (hour != dateHour && !adjustedSearchStartDate) {
CFDateRef hourBegin = NULL;
CFTimeInterval hInv = 0.0;
do {
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &hourBegin, &hInv, result);
if (foundRange) {
CFIndex prevDateHour = dateHour;
CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hInv, hourBegin);
dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, tempSearchDate);
// Sometimes we can get into a position where the next hour is also equal to hour (as in we hit a backwards DST change). In this case, we could be at the first time this hour occurs. If we want the next time the hour is technically the same (as in we need to go to the second time this hour occurs), we check to see if we hit a backwards DST change.
CFDateRef possibleBackwardDSTDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hInv*2, hourBegin);
CFIndex secondDateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, possibleBackwardDSTDate);
if (((dateHour - prevDateHour) == 2) || (prevDateHour == 23 && dateHour == 1)) {
// We've hit a forward DST transition.
dateHour -= 1;
CFRelease(possibleBackwardDSTDate);
CFRelease(tempSearchDate);
CFRelease(result);
result = hourBegin;
} else if ((secondDateHour == dateHour) && findLastMatch) { // If we're not trying to find the last match, just pass on the match we already found.
// We've hit a backwards DST transition.
CFRelease(tempSearchDate);
CFRelease(hourBegin);
CFRelease(result);
result = possibleBackwardDSTDate;
} else {
CFRelease(possibleBackwardDSTDate);
CFRelease(hourBegin);
CFRelease(result);
result = tempSearchDate;
}
adjustedSearchStartDate = true;
}
} while (hour != dateHour);
CFComparisonResult order = CFDateCompare(originalStartDate, result, NULL);
if (goBackwards && (order == kCFCompareLessThan)) { // We've gone into the future when we were supposed to go into the past. We're ahead by a day.
CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitDay, result);
CFRelease(result);
result = tempResult;
// Check hours again to see if they match (they may not because of DST change already being handled implicitly by dateByAddingUnit:)
dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, result);
if ((dateHour - hour) == 1) { // Detecting a DST transition
// We have moved an hour ahead of where we want to be so we go back 1 hour to readjust.
CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitHour, result);
CFRelease(result);
result = tempResult;
} else if ((hour - dateHour) == 1) {
// <rdar://problem/31051045> NSCalendar enumerateDatesStartingAfterDate: returns nil for the day before a forward DST change when searching backwards
// This is a weird special edge case that only gets hit when you're searching backwards and move past a forward (skip an hour) DST transition.
// We're not at a DST transition but the hour of our date got moved because the previous day had a DST transition.
// So we're an hour before where we want to be. We move an hour ahead to correct and get back to where we need to be.
CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, 1, kCFCalendarUnitHour, result);
CFRelease(result);
result = tempResult;
}
}
}
if (findLastMatch) {
CFDateRef hourBegin = NULL;
CFTimeInterval hInv = 0.0;
// This does the same as above for detecting backwards DST changes except that it covers the case where dateHour is already equal to hour. In this case, we could be at the first time we hit an hour (if it falls in a DST transition). Note: the check here tends to be for time zones like Brazil/East where the transition happens at midnight.
Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &hourBegin, &hInv, result);
if (foundRange) {
// Rewind forward/back hour-by-hour until we get to a different hour. A loop here is necessary because not all DST transitions are only an hour long.
CFDateRef next = CFRetain(hourBegin);
CFIndex nextHour = hour;
while (nextHour == hour) {
CFRelease(result);
result = next;
next = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, (goBackwards ? -1 : 1), kCFCalendarUnitHour, next);
nextHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, next);
}
CFRelease(next);
CFRelease(hourBegin);
adjustedSearchStartDate = YES;
}
}
if (!adjustedSearchStartDate) {
// This applies if we didn't hit the above cases to adjust the search start date, i.e. the hour already matches the start hour and either:
// 1) We're not looking to match the "last" (repeated) hour in a DST transition (regardless of whether we're in a DST transition), or
// 2) We are looking to match that hour, but we're not in that DST transition.
//
// In either case, we need to clear the lower components in case they are not part of the components we're looking for.
CFDateRef hourBegin = NULL;
CFTimeInterval hInv = 0.0;