forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSCalendar.swift
1532 lines (1337 loc) · 73 KB
/
NSCalendar.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
@_implementationOnly import CoreFoundation
internal let kCFCalendarUnitEra = CFCalendarUnit.era
internal let kCFCalendarUnitYear = CFCalendarUnit.year
internal let kCFCalendarUnitMonth = CFCalendarUnit.month
internal let kCFCalendarUnitDay = CFCalendarUnit.day
internal let kCFCalendarUnitHour = CFCalendarUnit.hour
internal let kCFCalendarUnitMinute = CFCalendarUnit.minute
internal let kCFCalendarUnitSecond = CFCalendarUnit.second
internal let kCFCalendarUnitWeekday = CFCalendarUnit.weekday
internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.weekdayOrdinal
internal let kCFCalendarUnitQuarter = CFCalendarUnit.quarter
internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.weekOfMonth
internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.weekOfYear
internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.yearForWeekOfYear
internal let kCFCalendarUnitNanosecond = CFCalendarUnit(rawValue: CFOptionFlags(CoreFoundation.kCFCalendarUnitNanosecond))
internal func _CFCalendarUnitRawValue(_ unit: CFCalendarUnit) -> CFOptionFlags {
return unit.rawValue
}
internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle
internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle
internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle
internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle
internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle
extension NSCalendar {
public struct Identifier : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public static let gregorian = NSCalendar.Identifier("gregorian")
public static let buddhist = NSCalendar.Identifier("buddhist")
public static let chinese = NSCalendar.Identifier("chinese")
public static let coptic = NSCalendar.Identifier("coptic")
public static let ethiopicAmeteMihret = NSCalendar.Identifier("ethiopic")
public static let ethiopicAmeteAlem = NSCalendar.Identifier("ethiopic-amete-alem")
public static let hebrew = NSCalendar.Identifier("hebrew")
public static let ISO8601 = NSCalendar.Identifier("iso8601")
public static let indian = NSCalendar.Identifier("indian")
public static let islamic = NSCalendar.Identifier("islamic")
public static let islamicCivil = NSCalendar.Identifier("islamic-civil")
public static let japanese = NSCalendar.Identifier("japanese")
public static let persian = NSCalendar.Identifier("persian")
public static let republicOfChina = NSCalendar.Identifier("roc")
public static let islamicTabular = NSCalendar.Identifier("islamic-tbla")
public static let islamicUmmAlQura = NSCalendar.Identifier("islamic-umalqura")
}
public struct Unit: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let era = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitEra))
public static let year = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYear))
public static let month = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMonth))
public static let day = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitDay))
public static let hour = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitHour))
public static let minute = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMinute))
public static let second = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitSecond))
public static let weekday = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekday))
public static let weekdayOrdinal = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekdayOrdinal))
public static let quarter = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitQuarter))
public static let weekOfMonth = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfMonth))
public static let weekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfYear))
public static let yearForWeekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYearForWeekOfYear))
public static let nanosecond = Unit(rawValue: UInt(1 << 15))
public static let calendar = Unit(rawValue: UInt(1 << 20))
public static let timeZone = Unit(rawValue: UInt(1 << 21))
internal var _cfValue: CFCalendarUnit {
return CFCalendarUnit(rawValue: self.rawValue)
}
}
public struct Options : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let wrapComponents = Options(rawValue: 1 << 0)
public static let matchStrictly = Options(rawValue: 1 << 1)
public static let searchBackwards = Options(rawValue: 1 << 2)
public static let matchPreviousTimePreservingSmallerUnits = Options(rawValue: 1 << 8)
public static let matchNextTimePreservingSmallerUnits = Options(rawValue: 1 << 9)
public static let matchNextTime = Options(rawValue: 1 << 10)
public static let matchFirst = Options(rawValue: 1 << 12)
public static let matchLast = Options(rawValue: 1 << 13)
}
}
extension NSCalendar.Identifier {
public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
open class NSCalendar : NSObject, NSCopying, NSSecureCoding {
typealias CFType = CFCalendar
private var _base = _CFInfo(typeID: CFCalendarGetTypeID())
private var _identifier: UnsafeMutableRawPointer? = nil
private var _locale: UnsafeMutableRawPointer? = nil
private var _tz: UnsafeMutableRawPointer? = nil
private var _firstWeekday: Int = 0
private var _minDaysInFirstWeek: Int = 0
private var _gregorianStart: UnsafeMutableRawPointer? = nil
private var _cal: UnsafeMutableRawPointer? = nil
private var _userSet_firstWeekday: Bool = false
private var _userSet_minDaysInFirstWeek: Bool = false
private var _userSet_gregorianStart: Bool = false
internal var _cfObject: CFType {
return unsafeBitCast(self, to: CFCalendar.self)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let calendarIdentifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else {
return nil
}
self.init(identifier: NSCalendar.Identifier.init(rawValue: calendarIdentifier._swiftObject))
if aDecoder.containsValue(forKey: "NS.timezone") {
if let timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone") {
self.timeZone = timeZone._swiftObject
}
}
if aDecoder.containsValue(forKey: "NS.locale") {
if let locale = aDecoder.decodeObject(of: NSLocale.self, forKey: "NS.locale") {
self.locale = locale._swiftObject
}
}
self.firstWeekday = aDecoder.decodeInteger(forKey: "NS.firstwkdy")
self.minimumDaysInFirstWeek = aDecoder.decodeInteger(forKey: "NS.mindays")
if aDecoder.containsValue(forKey: "NS.gstartdate") {
if let startDate = aDecoder.decodeObject(of: NSDate.self, forKey: "NS.gstartdate") {
self.gregorianStartDate = startDate._swiftObject
}
}
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.calendarIdentifier.rawValue._bridgeToObjectiveC(), forKey: "NS.identifier")
aCoder.encode(self.timeZone._nsObject, forKey: "NS.timezone")
aCoder.encode(self.locale?._bridgeToObjectiveC(), forKey: "NS.locale")
aCoder.encode(self.firstWeekday, forKey: "NS.firstwkdy")
aCoder.encode(self.minimumDaysInFirstWeek, forKey: "NS.mindays")
aCoder.encode(self.gregorianStartDate?._nsObject, forKey: "NS.gstartdate")
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSCalendar(identifier: calendarIdentifier)!
copy.locale = locale
copy.timeZone = timeZone
copy.firstWeekday = firstWeekday
copy.minimumDaysInFirstWeek = minimumDaysInFirstWeek
copy.gregorianStartDate = gregorianStartDate
return copy
}
open class var current: Calendar {
return Calendar.current
}
open class var autoupdatingCurrent: Calendar {
// swift-corelibs-foundation does not yet support autoupdating, but we can return the current calendar (which will not change).
return Calendar.autoupdatingCurrent
}
public /*not inherited*/ init?(identifier calendarIdentifierConstant: Identifier) {
super.init()
if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant.rawValue._cfObject) {
return nil
}
}
public init?(calendarIdentifier ident: Identifier) {
super.init()
if !_CFCalendarInitWithIdentifier(_cfObject, ident.rawValue._cfObject) {
return nil
}
}
internal override init() {
super.init()
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
if let value = value, self === value as AnyObject {
return true
}
if let calendar = __SwiftValue.fetch(value as AnyObject) as? NSCalendar {
return calendar.calendarIdentifier == calendarIdentifier &&
calendar.timeZone == timeZone &&
calendar.locale == locale &&
calendar.firstWeekday == firstWeekday &&
calendar.minimumDaysInFirstWeek == minimumDaysInFirstWeek &&
calendar.gregorianStartDate == gregorianStartDate
}
return false
}
open override var description: String {
return CFCopyDescription(_cfObject)._swiftObject
}
deinit {
_CFDeinit(self)
}
open var calendarIdentifier: Identifier {
get {
return Identifier(rawValue: CFCalendarGetIdentifier(_cfObject)._swiftObject)
}
}
/*@NSCopying*/ open var locale: Locale? {
get {
return CFCalendarCopyLocale(_cfObject)._swiftObject
}
set {
CFCalendarSetLocale(_cfObject, newValue?._cfObject)
}
}
/*@NSCopying*/ open var timeZone: TimeZone {
get {
return CFCalendarCopyTimeZone(_cfObject)._swiftObject
}
set {
CFCalendarSetTimeZone(_cfObject, newValue._cfObject)
}
}
open var firstWeekday: Int {
get {
return CFCalendarGetFirstWeekday(_cfObject)
}
set {
CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue))
}
}
open var minimumDaysInFirstWeek: Int {
get {
return CFCalendarGetMinimumDaysInFirstWeek(_cfObject)
}
set {
CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue))
}
}
internal var gregorianStartDate: Date? {
get {
return CFCalendarCopyGregorianStartDate(_cfObject)?._swiftObject
}
set {
let date = newValue as NSDate?
CFCalendarSetGregorianStartDate(_cfObject, date?._cfObject)
}
}
// Methods to return component name strings localized to the calendar's locale
private final func _symbols(_ key: CFString) -> [String] {
let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle)
CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject)
let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! NSArray)._swiftObject
return result.map {
return ($0 as! NSString)._swiftObject
}
}
private final func _symbol(_ key: CFString) -> String {
let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._bridgeToObjectiveC()._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle)
CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject)
return (CFDateFormatterCopyProperty(dateFormatter, key) as! NSString)._swiftObject
}
open var eraSymbols: [String] {
return _symbols(kCFDateFormatterEraSymbolsKey)
}
open var longEraSymbols: [String] {
return _symbols(kCFDateFormatterLongEraSymbolsKey)
}
open var monthSymbols: [String] {
return _symbols(kCFDateFormatterMonthSymbolsKey)
}
open var shortMonthSymbols: [String] {
return _symbols(kCFDateFormatterShortMonthSymbolsKey)
}
open var veryShortMonthSymbols: [String] {
return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey)
}
open var standaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey)
}
open var shortStandaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey)
}
open var veryShortStandaloneMonthSymbols: [String] {
return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey)
}
open var weekdaySymbols: [String] {
return _symbols(kCFDateFormatterWeekdaySymbolsKey)
}
open var shortWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterShortWeekdaySymbolsKey)
}
open var veryShortWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey)
}
open var standaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey)
}
open var shortStandaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey)
}
open var veryShortStandaloneWeekdaySymbols: [String] {
return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey)
}
open var quarterSymbols: [String] {
return _symbols(kCFDateFormatterQuarterSymbolsKey)
}
open var shortQuarterSymbols: [String] {
return _symbols(kCFDateFormatterShortQuarterSymbolsKey)
}
open var standaloneQuarterSymbols: [String] {
return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey)
}
open var shortStandaloneQuarterSymbols: [String] {
return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey)
}
open var amSymbol: String {
return _symbol(kCFDateFormatterAMSymbolKey)
}
open var pmSymbol: String {
return _symbol(kCFDateFormatterPMSymbolKey)
}
// Calendrical calculations
open func minimumRange(of unit: Unit) -> NSRange {
let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue)
if (r.location == kCFNotFound) {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func maximumRange(of unit: Unit) -> NSRange {
let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue)
if r.location == kCFNotFound {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func range(of smaller: Unit, in larger: Unit, for date: Date) -> NSRange {
let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)
if r.location == kCFNotFound {
return NSRange(location: NSNotFound, length: NSNotFound)
}
return NSRange(location: r.location, length: r.length)
}
open func ordinality(of smaller: Unit, in larger: Unit, for date: Date) -> Int {
return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate))
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func rangeOfUnit(_ unit: Unit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool
/// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func range(of unit: Unit, for date: Date) -> DateInterval? {
var start: CFAbsoluteTime = 0.0
var ti: CFTimeInterval = 0.0
let res: Bool = withUnsafeMutablePointer(to: &start) { startp in
withUnsafeMutablePointer(to: &ti) { tip in
return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip)
}
}
if res {
return DateInterval(start: Date(timeIntervalSinceReferenceDate: start), duration: ti)
}
return nil
}
private func _convert(_ comp: Int?, type: String, vector: inout [Int32], compDesc: inout [Int8]) {
if let component = comp {
vector.append(Int32(component))
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _convert(_ comp: Bool?, type: String, vector: inout [Int32], compDesc: inout [Int8]) {
if let component = comp {
vector.append(Int32(component ? 0 : 1))
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _convert(_ comps: DateComponents) -> (Array<Int32>, Array<Int8>) {
var vector = [Int32]()
var compDesc = [Int8]()
_convert(comps.era, type: "G", vector: &vector, compDesc: &compDesc)
_convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc)
_convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc)
if comps.weekOfYear != NSDateComponentUndefined {
_convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc)
} else {
// _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc)
}
_convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc)
_convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc)
_convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc)
_convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc)
_convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc)
_convert(comps.isLeapMonth, type: "l", vector: &vector, compDesc: &compDesc)
_convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc)
_convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc)
_convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc)
_convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc)
_convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc)
compDesc.append(0)
return (vector, compDesc)
}
open func date(from comps: DateComponents) -> Date? {
var (vector, compDesc) = _convert(comps)
let oldTz = self.timeZone
self.timeZone = comps.timeZone ?? timeZone
var at: CFAbsoluteTime = 0.0
let res: Bool = withUnsafeMutablePointer(to: &at) { t in
return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in
return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress!, Int32(vectorBuffer.count))
}
}
self.timeZone = oldTz
if res {
return Date(timeIntervalSinceReferenceDate: at)
} else {
return nil
}
}
private func _setup(_ unitFlags: Unit, field: Unit, type: String, compDesc: inout [Int8]) {
if unitFlags.contains(field) {
compDesc.append(Int8(type.utf8[type.utf8.startIndex]))
}
}
private func _setup(_ unitFlags: Unit, addIsLeapMonth: Bool = true) -> [Int8] {
var compDesc = [Int8]()
_setup(unitFlags, field: .era, type: "G", compDesc: &compDesc)
_setup(unitFlags, field: .year, type: "y", compDesc: &compDesc)
_setup(unitFlags, field: .quarter, type: "Q", compDesc: &compDesc)
_setup(unitFlags, field: .weekOfYear, type: "w", compDesc: &compDesc)
_setup(unitFlags, field: .month, type: "M", compDesc: &compDesc)
if addIsLeapMonth {
_setup(unitFlags, field: .month, type: "l", compDesc: &compDesc)
}
_setup(unitFlags, field: .weekOfMonth, type: "W", compDesc: &compDesc)
_setup(unitFlags, field: .yearForWeekOfYear, type: "Y", compDesc: &compDesc)
_setup(unitFlags, field: .weekday, type: "E", compDesc: &compDesc)
_setup(unitFlags, field: .weekdayOrdinal, type: "F", compDesc: &compDesc)
_setup(unitFlags, field: .day, type: "d", compDesc: &compDesc)
_setup(unitFlags, field: .hour, type: "H", compDesc: &compDesc)
_setup(unitFlags, field: .minute, type: "m", compDesc: &compDesc)
_setup(unitFlags, field: .second, type: "s", compDesc: &compDesc)
_setup(unitFlags, field: .nanosecond, type: "#", compDesc: &compDesc)
compDesc.append(0)
return compDesc
}
private func _setComp(_ unitFlags: Unit, field: Unit, vector: [Int32], compIndex: inout Int, setter: (Int32) -> Void) {
if unitFlags.contains(field) {
setter(vector[compIndex])
compIndex += 1
}
}
private func _components(_ unitFlags: Unit, vector: [Int32], addIsLeapMonth: Bool = true) -> DateComponents {
var compIdx = 0
var comps = DateComponents()
_setComp(unitFlags, field: .era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) }
_setComp(unitFlags, field: .year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) }
_setComp(unitFlags, field: .quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) }
_setComp(unitFlags, field: .weekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) }
_setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) }
if addIsLeapMonth {
_setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.isLeapMonth = $0 != 0 }
}
_setComp(unitFlags, field: .weekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) }
_setComp(unitFlags, field: .yearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) }
_setComp(unitFlags, field: .weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) }
_setComp(unitFlags, field: .weekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) }
_setComp(unitFlags, field: .day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) }
_setComp(unitFlags, field: .hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) }
_setComp(unitFlags, field: .minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) }
_setComp(unitFlags, field: .second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) }
_setComp(unitFlags, field: .nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) }
if unitFlags.contains(.calendar) {
comps.calendar = self._swiftObject
}
if unitFlags.contains(.timeZone) {
comps.timeZone = timeZone
}
return comps
}
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil
open func components(_ unitFlags: Unit, from date: Date) -> DateComponents {
let compDesc = _setup(unitFlags)
// _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format
// int32_t ints[20];
// int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]};
var ints = [Int32](repeating: 0, count: 20)
let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in
var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in
intArrayBuffer.baseAddress!.advanced(by: idx)
}
return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in
return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress!, Int32(compDesc.count - 1))
}
}
if res {
return _components(unitFlags, vector: ints)
}
fatalError()
}
open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? {
var (vector, compDesc) = _convert(comps)
var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate
let res: Bool = withUnsafeMutablePointer(to: &at) { t in
let count = Int32(vector.count)
return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in
return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress!, count)
}
}
if res {
return Date(timeIntervalSinceReferenceDate: at)
}
return nil
}
open func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents {
let validUnitFlags: NSCalendar.Unit = [
.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekOfYear, .weekOfMonth, .yearForWeekOfYear, .weekday, .weekdayOrdinal ]
let invalidUnitFlags: NSCalendar.Unit = [ .quarter, .timeZone, .calendar]
// Mask off the unsupported fields
let newUnitFlags = Unit(rawValue: unitFlags.rawValue & validUnitFlags.rawValue)
let compDesc = _setup(newUnitFlags, addIsLeapMonth: false)
var ints = [Int32](repeating: 0, count: 20)
let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in
var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in
return intArrayBuffer.baseAddress!.advanced(by: idx)
}
let count = Int32(vector.count)
return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in
return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, count)
}
}
if res {
let emptyUnitFlags = Unit(rawValue: unitFlags.rawValue & invalidUnitFlags.rawValue)
var components = _components(newUnitFlags, vector: ints, addIsLeapMonth: false)
// quarter always gets set to zero if requested in the output
if emptyUnitFlags.contains(.quarter) {
components.quarter = 0
}
// isLeapMonth is always set
components.isLeapMonth = false
return components
}
fatalError()
}
/*
This API is a convenience for getting era, year, month, and day of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.era, .year, .month, .day], from: date)
eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined
yearValuePointer?.pointee = comps.year ?? NSDateComponentUndefined
monthValuePointer?.pointee = comps.month ?? NSDateComponentUndefined
dayValuePointer?.pointee = comps.day ?? NSDateComponentUndefined
}
/*
This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.era, .yearForWeekOfYear, .weekOfYear, .weekday], from: date)
eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined
yearValuePointer?.pointee = comps.yearForWeekOfYear ?? NSDateComponentUndefined
weekValuePointer?.pointee = comps.weekOfYear ?? NSDateComponentUndefined
weekdayValuePointer?.pointee = comps.weekday ?? NSDateComponentUndefined
}
/*
This API is a convenience for getting hour, minute, second, and nanoseconds of a given date.
Pass NULL for a NSInteger pointer parameter if you don't care about that value.
*/
open func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) {
let comps = components([.hour, .minute, .second, .nanosecond], from: date)
hourValuePointer?.pointee = comps.hour ?? NSDateComponentUndefined
minuteValuePointer?.pointee = comps.minute ?? NSDateComponentUndefined
secondValuePointer?.pointee = comps.second ?? NSDateComponentUndefined
nanosecondValuePointer?.pointee = comps.nanosecond ?? NSDateComponentUndefined
}
/*
Get just one component's value.
*/
open func component(_ unit: Unit, from date: Date) -> Int {
let comps = components(unit, from: date)
if let res = comps.value(for: Calendar._fromCalendarUnit(unit)) {
return res
} else {
return NSDateComponentUndefined
}
}
/*
Create a date with given components.
Current era is assumed.
*/
open func date(era eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? {
var comps = DateComponents()
comps.era = eraValue
comps.year = yearValue
comps.month = monthValue
comps.day = dayValue
comps.hour = hourValue
comps.minute = minuteValue
comps.second = secondValue
comps.nanosecond = nanosecondValue
return date(from: comps)
}
/*
Create a date with given components.
Current era is assumed.
*/
open func date(era eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? {
var comps = DateComponents()
comps.era = eraValue
comps.yearForWeekOfYear = yearValue
comps.weekOfYear = weekValue
comps.weekday = weekdayValue
comps.hour = hourValue
comps.minute = minuteValue
comps.second = secondValue
comps.nanosecond = nanosecondValue
return date(from: comps)
}
/*
This API returns the first moment date of a given date.
Pass in [NSDate date], for example, if you want the start of "today".
If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.
*/
open func startOfDay(for date: Date) -> Date {
return range(of: .day, for: date)!.start
}
/*
This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone).
The time zone overrides the time zone of the NSCalendar for the purposes of this calculation.
Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil
open func components(in timezone: TimeZone, from date: Date) -> DateComponents {
let oldTz = self.timeZone
self.timeZone = timezone
let comps = components([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone], from: date)
self.timeZone = oldTz
return comps
}
/*
This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than.
*/
open func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: Unit) -> ComparisonResult {
switch (unit) {
case .calendar:
return .orderedSame
case .timeZone:
return .orderedSame
case .day: fallthrough
case .hour:
let range = self.range(of: unit, for: date1)
let ats = range!.start.timeIntervalSinceReferenceDate
let at2 = date2.timeIntervalSinceReferenceDate
if ats <= at2 && at2 < ats + range!.duration {
return .orderedSame
}
if at2 < ats {
return .orderedDescending
}
return .orderedAscending
case .minute:
var int1 = 0.0
var int2 = 0.0
modf(date1.timeIntervalSinceReferenceDate, &int1)
modf(date2.timeIntervalSinceReferenceDate, &int2)
int1 = floor(int1 / 60.0)
int2 = floor(int2 / 60.0)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
case .second:
var int1 = 0.0
var int2 = 0.0
modf(date1.timeIntervalSinceReferenceDate, &int1)
modf(date2.timeIntervalSinceReferenceDate, &int2)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
case .nanosecond:
var int1 = 0.0
var int2 = 0.0
let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1)
let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2)
int1 = floor(frac1 * 1000000000.0)
int2 = floor(frac2 * 1000000000.0)
if int1 == int2 {
return .orderedSame
}
if int2 < int1 {
return .orderedDescending
}
return .orderedAscending
default:
break
}
let calendarUnits1: [Unit] = [.era, .year, .month, .day]
let calendarUnits2: [Unit] = [.era, .year, .month, .weekdayOrdinal, .day]
let calendarUnits3: [Unit] = [.era, .year, .month, .weekOfMonth, .weekday]
let calendarUnits4: [Unit] = [.era, .yearForWeekOfYear, .weekOfYear, .weekday]
var units: [Unit]
if unit == .yearForWeekOfYear || unit == .weekOfYear {
units = calendarUnits4
} else if unit == .weekdayOrdinal {
units = calendarUnits2
} else if unit == .weekday || unit == .weekOfMonth {
units = calendarUnits3
} else {
units = calendarUnits1
}
// TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret
let reducedUnits = units.reduce(Unit()) { $0.union($1) }
let comp1 = components(reducedUnits, from: date1)
let comp2 = components(reducedUnits, from: date2)
for testedUnit in units {
let value1 = comp1.value(for: Calendar._fromCalendarUnit(testedUnit))
let value2 = comp2.value(for: Calendar._fromCalendarUnit(testedUnit))
if value1! > value2! {
return .orderedDescending
} else if value1! < value2! {
return .orderedAscending
}
if testedUnit == .month && calendarIdentifier == .chinese {
if let leap1 = comp1.isLeapMonth {
if let leap2 = comp2.isLeapMonth {
if !leap1 && leap2 {
return .orderedAscending
} else if leap1 && !leap2 {
return .orderedDescending
}
}
}
}
if testedUnit == unit {
return .orderedSame
}
}
return .orderedSame
}
/*
This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units.
*/
open func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: Unit) -> Bool {
return compare(date1, to: date2, toUnitGranularity: unit) == .orderedSame
}
/*
This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
open func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool {
return compare(date1, to: date2, toUnitGranularity: .day) == .orderedSame
}
/*
This API reports if the date is within "today".
*/
open func isDateInToday(_ date: Date) -> Bool {
return compare(date, to: Date(), toUnitGranularity: .day) == .orderedSame
}
/*
This API reports if the date is within "yesterday".
*/
open func isDateInYesterday(_ date: Date) -> Bool {
if let interval = range(of: .day, for: Date()) {
let inYesterday = interval.start - 60.0
return compare(date, to: inYesterday, toUnitGranularity: .day) == .orderedSame
} else {
return false
}
}
/*
This API reports if the date is within "tomorrow".
*/
open func isDateInTomorrow(_ date: Date) -> Bool {
if let interval = range(of: .day, for: Date()) {
let inTomorrow = interval.end + 60.0
return compare(date, to: inTomorrow, toUnitGranularity: .day) == .orderedSame
} else {
return false
}
}
/*
This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale.
*/
open func isDateInWeekend(_ date: Date) -> Bool {
return _CFCalendarIsDateInWeekend(_cfObject, date._cfObject)
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func rangeOfWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool
/// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer.
/// Find the range of the weekend around the given date, returned via two by-reference parameters.
/// Returns nil if the given date is not in a weekend.
/// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func range(ofWeekendContaining date: Date) -> DateInterval? {
if let next = nextWeekendAfter(date, options: []) {
if let prev = nextWeekendAfter(next.start, options: .searchBackwards) {
if prev.start <= date && date < prev.end /* exclude the end since it's the start of the next day */ {
return prev
}
}
}
return nil
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer.
/// The current exposed API in Foundation on Darwin platforms is:
/// open func nextWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: Options, afterDate date: NSDate) -> Bool
/// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date.
/// The .SearchBackwards option can be used to find the previous weekend range strictly before the date.
/// Returns nil if there are no such things as weekend in the calendar and its locale.
/// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func nextWeekendAfter(_ date: Date, options: Options) -> DateInterval? {
var range = _CFCalendarWeekendRange()
let res = withUnsafeMutablePointer(to: &range) { rangep in
return _CFCalendarGetNextWeekend(_cfObject, rangep)
}
if res {
var comp = DateComponents()
comp.weekday = range.start
if let nextStart = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) {
let start = startOfDay(for: nextStart + range.onsetTime)
comp.weekday = range.end
if let nextEnd = nextDate(after: start, matching: comp, options: .matchNextTime) {
var end = nextEnd
if range.ceaseTime > 0 {
end = end + range.ceaseTime
} else {
if let dayEnd = self.range(of: .day, for: end) {
end = startOfDay(for: dayEnd.end)
} else {
return nil
}
}
return DateInterval(start: start, end: end)
}
}
}
return nil
}
/*
This API returns the difference between two dates specified as date components.
For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed.
Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised.
For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property.
No options are currently defined; pass 0.
*/
open func components(_ unitFlags: Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: Options = []) -> DateComponents {
var startDate: Date?
var toDate: Date?
if let startCalendar = startingDateComp.calendar {
startDate = startCalendar.date(from: startingDateComp)
} else {
startDate = date(from: startingDateComp)
}