-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathDateAndTime.swift
1007 lines (814 loc) · 25.8 KB
/
DateAndTime.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
//
// DateAndTime.swift
// SwiftFHIR
//
// Created by Pascal Pfiffner on 1/17/15.
// 2015, SMART Health IT.
//
import Foundation
/**
A protocol for all our date and time structs.
*/
protocol DateAndTime: FHIRPrimitive, CustomStringConvertible, Comparable {
var nsDate: Date { get }
init?(string: String)
}
// MARK: -
/**
A date for use in human communication. Named `FHIRDate` to avoid the numerous collisions with `Foundation.Date`.
Month and day are optional and there are no timezones.
*/
public struct FHIRDate: DateAndTime {
/// The year.
public var year: Int
/// The month of the year, maximum of 12.
public var month: UInt8? {
didSet {
if let mth = month, mth > 12 {
month = nil
}
}
}
/// The day of the month; must be valid for the month (not enforced in code!).
public var day: UInt8? {
didSet {
if let d = day, d > 31 {
day = nil
}
}
}
/// An optional id of the element.
public var id: String?
/// The parent/owner of the receiver, if any. Used to dereference resources.
public weak var _owner: FHIRAbstractBase?
/// Optional extensions of the element.
public var extension_fhir: [Extension]?
/// Today's date.
public static var today: FHIRDate {
let (date, _, _) = DateNSDateConverter.shared.parse(date: Date())
return date
}
/**
Designated initializer. Everything but the year is optional, invalid months or days will be ignored (however it is NOT checked whether
the given month indeed contains the given day).
- parameter year: The year of the date
- parameter month: The month of the year
- parameter day: The day of the month – your responsibility to ensure the month has the desired number of days; ignored if no month is
given
*/
public init(year: Int, month: UInt8?, day: UInt8?) {
self.year = year
if let mth = month, mth <= 12 {
self.month = mth
if let d = day, d <= 31 {
self.day = d
}
}
}
/**
Initializes a date with our `DateAndTimeParser`.
Will fail unless the string contains at least a valid year.
- parameter string: The string to parse the date from
*/
public init?(string: String) {
do {
var ctx = FHIRInstantiationContext()
self.init(json: string, owner: nil, context: &ctx)
try ctx.validate()
}
catch let error {
fhir_logIfDebug("\(error)")
return nil
}
}
// MARK: FHIRJSONType
public typealias JSONType = String
public init(json: JSONType, owner: FHIRAbstractBase?, context: inout FHIRInstantiationContext) {
if let date = DateAndTimeParser.shared.parse(string: json).date {
year = date.year
month = date.month
day = date.day
}
else {
context.addError(FHIRValidationError(key: "", problem: "the string “\(json)” could not be parsed into a \(type(of: self))"))
year = 0
}
_owner = owner
}
public func asJSON(errors: inout [FHIRValidationError]) -> JSONType {
return description
}
// MARK: Protocols
public var nsDate: Date {
return DateNSDateConverter.shared.create(fromDate: self)
}
public var description: String {
if let m = month {
if let d = day {
return String(format: "%04d-%02d-%02d", year, m, d)
}
return String(format: "%04d-%02d", year, m)
}
return String(format: "%04d", year)
}
// MARK: Equatable, Comparable
public static func ==(lhs: FHIRDate, rhs: FHIRDate) -> Bool {
return lhs.year == rhs.year
&& lhs.month == rhs.month
&& lhs.day == rhs.day
}
public static func <(lhs: FHIRDate, rhs: FHIRDate) -> Bool {
if lhs.year == rhs.year {
guard let lhm = lhs.month else {
return true
}
guard let rhm = rhs.month else {
return false
}
if lhm == rhm {
guard let lhd = lhs.day else {
return true
}
guard let rhd = rhs.day else {
return false
}
return lhd < rhd
}
return lhm < rhm
}
return lhs.year < rhs.year
}
}
// MARK: -
/**
A time during the day, optionally with seconds, usually for human communication. Named `FHIRTime` to match with `FHIRDate`.
Minimum of 00:00 and maximum of < 24:00. There is no timezone. Since decimal precision has significance in FHIR, Time initialized from a
string will remember the seconds string until it is manually set.
*/
public struct FHIRTime: DateAndTime {
/// The hour of the day; cannot be higher than 23.
public var hour: UInt8 {
didSet {
if hour > 23 {
hour = 23
}
}
}
/// The minute of the hour; cannot be larger than 59
public var minute: UInt8 {
didSet {
if minute > 59 {
minute = 59
}
}
}
/// The second of the minute; must be smaller than 60
public var second: Double? {
didSet {
if let sec = second, sec >= 60.0 {
second = 59.999999999
}
tookSecondsFromString = nil
}
}
/// If initialized from string, this was the string for the seconds; we use this to remember precision.
public internal(set) var tookSecondsFromString: String?
/// An optional id of the element.
public var id: String?
/// The parent/owner of the receiver, if any. Used to dereference resources.
public weak var _owner: FHIRAbstractBase?
/// Optional extensions of the element.
public var extension_fhir: [Extension]?
/// The clock time of right now.
public static var now: FHIRTime {
let (_, time, _) = DateNSDateConverter.shared.parse(date: Date())
return time
}
/**
Designated initializer. Overflows seconds and minutes to arrive at the final time, which must be less than 24:00:00 or it will be capped.
The `secondsFromString` parameter will be discarded if it is negative or higher than 60.
- parameter hour: Hour of day, cannot be greater than 23 (a time of 24:00 is illegal)
- parameter minute: Minutes of the hour; if greater than 59 will roll over into hours
- parameter second: Seconds of the minute; if 60 or more will roll over into minutes and discard `secondsFromString`
- parameter secondsFromString: If time was initialized from a string, you can provide the seconds string here to ensure precision is
kept. You are responsible to ensure that this string actually represents what's passed into `seconds`.
*/
public init(hour: UInt8, minute: UInt8, second: Double?, secondsFromString: String? = nil) {
var overflowMinute: UInt = 0
var overflowHour: UInt = 0
if let sec = second, sec >= 0.0 {
if sec >= 60.0 {
self.second = sec.truncatingRemainder(dividingBy: 60)
overflowMinute = UInt((sec - self.second!) / 60)
}
else {
self.second = sec
self.tookSecondsFromString = secondsFromString
}
}
let mins = UInt(minute) + overflowMinute
if mins > 59 {
self.minute = UInt8(mins % 60)
overflowHour = (mins - (mins % 60)) / 60
}
else {
self.minute = UInt8(mins)
}
let hrs = UInt(hour) + overflowHour
if hrs > 23 {
self.hour = 23
self.minute = 59
self.second = 59.999999999
self.tookSecondsFromString = nil
}
else {
self.hour = UInt8(hrs)
}
}
/**
Initializes a time from a time string by passing it through `DateAndTimeParser`.
Will fail unless the string contains at least hour and minute.
*/
public init?(string: String) {
do {
var ctx = FHIRInstantiationContext()
self.init(json: string, owner: nil, context: &ctx)
try ctx.validate()
}
catch let error {
fhir_logIfDebug("\(error)")
return nil
}
}
// MARK: FHIRJSONType
public typealias JSONType = String
public init(json: JSONType, owner: FHIRAbstractBase?, context: inout FHIRInstantiationContext) {
if let time = DateAndTimeParser.shared.parse(string: json, isTimeOnly: true).time {
hour = time.hour
minute = time.minute
second = time.second
tookSecondsFromString = time.tookSecondsFromString
}
else {
context.addError(FHIRValidationError(key: "", problem: "the string “\(json)” could not be parsed into a \(type(of: self))"))
hour = 0
minute = 0
}
_owner = owner
}
public func asJSON(errors: inout [FHIRValidationError]) -> JSONType {
return description
}
// MARK: Protocols
public var nsDate: Date {
return DateNSDateConverter.shared.create(fromTime: self)
}
// TODO: this implementation uses a workaround using string coercion instead of format: "%02d:%02d:%@" because %@ with String is not
// supported on Linux (SR-957)
public var description: String {
if let secStr = tookSecondsFromString {
#if os(Linux)
return String(format: "%02d:%02d:", hour, minute) + secStr
#else
return String(format: "%02d:%02d:%@", hour, minute, secStr)
#endif
}
if let s = second {
#if os(Linux)
return String(format: "%02d:%02d:", hour, minute) + ((s < 10.0) ? "0" : "") + String(format: "%g", s)
#else
return String(format: "%02d:%02d:%@%g", hour, minute, (s < 10.0) ? "0" : "", s)
#endif
}
return String(format: "%02d:%02d", hour, minute)
}
// MARK: Equatable, Comparable
public static func ==(lhs: FHIRTime, rhs: FHIRTime) -> Bool {
if nil != lhs.second && nil != rhs.second {
return lhs.description == rhs.description // must respect decimal precision of seconds, which `description` takes care of
}
return lhs.hour == rhs.hour
&& lhs.minute == rhs.minute
&& lhs.second == rhs.second
}
public static func <(lhs: FHIRTime, rhs: FHIRTime) -> Bool {
if lhs.hour == rhs.hour {
if lhs.minute == rhs.minute {
guard let lhsec = lhs.second else {
return true
}
guard let rhsec = rhs.second else {
return false
}
return lhsec < rhsec
}
return lhs.minute < rhs.minute
}
return lhs.hour < rhs.hour
}
}
// MARK: -
/**
A date, optionally with time, as used in human communication.
If a time is specified there must be a timezone; defaults to the system reported local timezone.
*/
public struct DateTime: DateAndTime {
/// The date.
public var date: FHIRDate
/// The time.
public var time: FHIRTime?
/// The timezone
public var timeZone: TimeZone? {
didSet {
timeZoneString = nil
}
}
/// The timezone string seen during deserialization; to be used on serialization unless the timezone changed.
var timeZoneString: String?
/// An optional id of the element.
public var id: String?
/// The parent/owner of the receiver, if any. Used to dereference resources.
public weak var _owner: FHIRAbstractBase?
/// Optional extensions of the element.
public var extension_fhir: [Extension]?
/// This very date and time: a DateTime instance representing current date and time.
public static var now: DateTime {
let (date, time, tz) = DateNSDateConverter.shared.parse(date: Date())
return DateTime(date: date, time: time, timeZone: tz)
}
/**
Designated initializer, takes a date and optionally a time and a timezone.
If time is given but no timezone, the instance is assigned the local time zone.
- parameter date: The date of the date-time
- parameter time: The time of the date-time
- parameter timeZone: The timezone
*/
public init(date: FHIRDate, time: FHIRTime?, timeZone: TimeZone?) {
self.date = date
self.time = time
if nil != time && nil == timeZone {
self.timeZone = TimeZone.current
}
else {
self.timeZone = timeZone
}
}
/**
Uses `DateAndTimeParser` to initialize from a date-time string.
If time is given but no timezone, the instance is assigned the local time zone.
- parameter string: The string the date-time is parsed from
*/
public init?(string: String) {
do {
var ctx = FHIRInstantiationContext()
self.init(json: string, owner: nil, context: &ctx)
try ctx.validate()
}
catch let error {
fhir_logIfDebug("\(error)")
return nil
}
}
// MARK: FHIRJSONType
public typealias JSONType = String
public init(json: JSONType, owner: FHIRAbstractBase?, context: inout FHIRInstantiationContext) {
let dt = DateAndTimeParser.shared.parse(string: json)
if let date = dt.date {
self.date = date
if let time = dt.time {
self.time = time
self.timeZone = dt.tz ?? TimeZone.current
self.timeZoneString = dt.tzString
}
}
else {
context.addError(FHIRValidationError(key: "", problem: "the string “\(json)” could not be parsed into a \(type(of: self))"))
date = FHIRDate(year: 0, month: nil, day: nil)
}
_owner = owner
}
public func asJSON(errors: inout [FHIRValidationError]) -> JSONType {
return description
}
// MARK: Protocols
public var nsDate: Date {
if let time = time, let tz = timeZone {
return DateNSDateConverter.shared.create(date: date, time: time, timeZone: tz)
}
return DateNSDateConverter.shared.create(fromDate: date)
}
public var description: String {
if let tm = time {
if let tz = timeZoneString ?? timeZone?.offset() {
return "\(date.description)T\(tm.description)\(tz)"
}
}
return date.description
}
// MARK: Equatable, Comparable
public static func ==(lhs: DateTime, rhs: DateTime) -> Bool {
let lhd = lhs.nsDate
let rhd = rhs.nsDate
return (lhd.compare(rhd) == .orderedSame)
}
public static func <(lhs: DateTime, rhs: DateTime) -> Bool {
let lhd = lhs.nsDate
let rhd = rhs.nsDate
return (lhd.compare(rhd) == .orderedAscending)
}
}
// MARK: -
/**
An instant in time, known at least to the second and with a timezone, for machine times.
*/
public struct Instant: DateAndTime {
/// The date.
public var date: FHIRDate {
didSet {
if nil == date.month {
date.month = 1
}
if nil == date.day {
date.day = 1
}
}
}
/// The time, including seconds.
public var time: FHIRTime {
didSet {
if nil == time.second {
time.second = 0.0
}
}
}
/// The timezone.
public var timeZone: TimeZone {
didSet {
timeZoneString = nil
}
}
/// The timezone string seen during deserialization; to be used on serialization unless the timezone changed.
var timeZoneString: String?
/// An optional id of the element.
public var id: String?
/// The parent/owner of the receiver, if any. Used to dereference resources.
public weak var _owner: FHIRAbstractBase?
/// Optional extensions of the element.
public var extension_fhir: [Extension]?
/// This very instant: an Instant instance representing current date and time.
public static var now: Instant {
let (date, time, tz) = DateNSDateConverter.shared.parse(date: Date())
return Instant(date: date, time: time, timeZone: tz)
}
/**
Designated initializer.
- parameter date: The date of the instant; ensures to have month and day (which are optional in the `FHIRDate` construct)
- parameter time: The time of the instant; ensures to have seconds (which are optional in the `FHIRTime` construct)
- parameter timeZone: The timezone
*/
public init(date: FHIRDate, time: FHIRTime, timeZone: TimeZone) {
self.date = date
if nil == self.date.month {
self.date.month = 1
}
if nil == self.date.day {
self.date.day = 1
}
self.time = time
if nil == self.time.second {
self.time.second = 0.0
}
self.timeZone = timeZone
}
/** Uses `DateAndTimeParser` to initialize from a date-time string.
- parameter string: The string to parse the instant from
*/
public init?(string: String) {
do {
var ctx = FHIRInstantiationContext()
self.init(json: string, owner: nil, context: &ctx)
try ctx.validate()
}
catch let error {
fhir_logIfDebug("\(error)")
return nil
}
}
// MARK: FHIRJSONType
public typealias JSONType = String
public init(json: JSONType, owner: FHIRAbstractBase?, context: inout FHIRInstantiationContext) {
let dt = DateAndTimeParser.shared.parse(string: json)
if let date = dt.date, let time = dt.time, let tz = dt.tz, let tzString = dt.tzString, nil != date.month, nil != date.day, nil != time.second {
self.date = date
self.time = time
self.timeZone = tz
self.timeZoneString = tzString
}
else {
date = FHIRDate(year: 0, month: nil, day: nil)
time = FHIRTime(hour: 0, minute: 0, second: nil)
timeZone = TimeZone(secondsFromGMT: 0)!
context.addError(FHIRValidationError(key: "", problem: "the string “\(json)” could not be parsed into a \(type(of: self))"))
}
_owner = owner
}
public func asJSON(errors: inout [FHIRValidationError]) -> JSONType {
return description
}
// MARK: Protocols
public var nsDate: Date {
return DateNSDateConverter.shared.create(date: date, time: time, timeZone: timeZone)
}
public var description: String {
let tz = timeZoneString ?? timeZone.offset()
return "\(date.description)T\(time.description)\(tz)"
}
// MARK: Equatable, Comparable
public static func ==(lhs: Instant, rhs: Instant) -> Bool {
let lhd = lhs.nsDate
let rhd = rhs.nsDate
return (lhd.compare(rhd) == .orderedSame)
}
public static func <(lhs: Instant, rhs: Instant) -> Bool {
let lhd = lhs.nsDate
let rhd = rhs.nsDate
return (lhd.compare(rhd) == .orderedAscending)
}
}
extension Instant {
/**
Attempts to parse an Instant from RFC1123-formatted date strings, usually used by HTTP headers:
- "EEE',' dd MMM yyyy HH':'mm':'ss z"
- "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z" (RFC850)
- "EEE MMM d HH':'mm':'ss yyyy"
Created by taking liberally from Marcus Rohrmoser's blogpost at http://blog.mro.name/2009/08/nsdateformatter-http-header/
- parameter httpDate: The date string to parse
- returns: An Instant if parsing was successful, nil otherwise
*/
public static func fromHttpDate(_ httpDate: String) -> Instant? {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "GMT")
formatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z"
if let date = formatter.date(from: httpDate) {
return date.fhir_asInstant()
}
formatter.dateFormat = "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z"
if let date = formatter.date(from: httpDate) {
return date.fhir_asInstant()
}
formatter.dateFormat = "EEE MMM d HH':'mm':'ss yyyy"
if let date = formatter.date(from: httpDate) {
return date.fhir_asInstant()
}
return nil
}
}
// MARK: -
/**
Converts between NSDate and our FHIRDate, FHIRTime, DateTime and Instance structs.
*/
class DateNSDateConverter {
/// The singleton instance
static var shared = DateNSDateConverter()
let calendar: Calendar
let utc: TimeZone
init() {
utc = TimeZone(abbreviation: "UTC")!
var cal = Calendar(identifier: Calendar.Identifier.gregorian)
cal.timeZone = utc
calendar = cal
}
// MARK: Parsing
/**
Execute parsing. Will use `calendar` to split the Date into components.
- parameter date: The Date to parse into structs
- returns: A tuple with (FHIRDate, FHIRTime, TimeZone)
*/
func parse(date inDate: Date) -> (FHIRDate, FHIRTime, TimeZone) {
let flags: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second, .nanosecond, .timeZone]
let comp = calendar.dateComponents(flags, from: inDate)
let date = FHIRDate(year: comp.year!, month: UInt8(comp.month!), day: UInt8(comp.day!))
let zone = comp.timeZone ?? utc
let secs = Double(comp.second!)
// on Ubuntu Linux - Swift 4 - comp.nanosecond is null
// + (Double(comp.nanosecond!) / 1000000000)
let time = FHIRTime(hour: UInt8(comp.hour!), minute: UInt8(comp.minute!), second: secs)
return (date, time, zone)
}
// MARK: Creation
func create(fromDate date: FHIRDate) -> Date {
return _create(date: date, time: nil, timeZone: nil)
}
func create(fromTime time: FHIRTime) -> Date {
return _create(date: nil, time: time, timeZone: nil)
}
func create(date: FHIRDate, time: FHIRTime, timeZone: TimeZone) -> Date {
return _create(date: date, time: time, timeZone: timeZone)
}
func _create(date: FHIRDate?, time: FHIRTime?, timeZone: TimeZone?) -> Date {
var comp = DateComponents()
comp.timeZone = timeZone ?? utc
if let yr = date?.year {
comp.year = yr
}
if let mth = date?.month {
comp.month = Int(mth)
}
if let d = date?.day {
comp.day = Int(d)
}
if let hr = time?.hour {
comp.hour = Int(hr)
}
if let min = time?.minute {
comp.minute = Int(min)
}
if let sec = time?.second {
comp.second = Int(floor(sec))
comp.nanosecond = Int(sec.truncatingRemainder(dividingBy: 1000000000))
}
return calendar.date(from: comp) ?? Date()
}
}
// MARK: -
/**
Parses Date and Time from strings in a narrow set of the extended ISO 8601 format.
*/
class DateAndTimeParser {
/// This struct is needed to prevent crashes on iOS devices (as of Xcode 8.2) when returning named tuples with FHIRDate and FHIRTime.
struct DT {
var date: FHIRDate?
var time: FHIRTime?
var tz: TimeZone?
var tzString: String?
}
/// The singleton instance
static var shared = DateAndTimeParser()
/**
Parses a date string in "YYYY[-MM[-DD]]" and a time string in "hh:mm[:ss[.sss]]" (extended ISO 8601) format,
separated by "T" and followed by either "Z" or a valid time zone offset in the "±hh[:?mm]" format.
Does not currently check if the day exists in the given month.
- parameter string: The date string to parse
- parameter isTimeOnly: If true assumes that the string describes time only
- returns: A tuple with (FHIRDate?, FHIRTime?, TimeZone?, String? [for time zone])
*/
func parse(string: String, isTimeOnly: Bool=false) -> DT {
let scanner = Scanner(string: string)
var date: FHIRDate?
var time: FHIRTime?
var tz: TimeZone?
var tzString: String?
// scan date (must have at least the year)
if !isTimeOnly {
if let year = scanner.fhir_scanInt(), year < 10000 { // dates above 9999 are considered special cases
if nil != scanner.fhir_scanString("-"), let month = scanner.fhir_scanInt(), month <= 12 {
if nil != scanner.fhir_scanString("-"), let day = scanner.fhir_scanInt(), day <= 31 {
date = FHIRDate(year: Int(year), month: UInt8(month), day: UInt8(day))
}
else {
date = FHIRDate(year: Int(year), month: UInt8(month), day: nil)
}
}
else {
date = FHIRDate(year: Int(year), month: nil, day: nil)
}
}
}
// scan time
if isTimeOnly || nil != scanner.fhir_scanString("T") {
if let hour = scanner.fhir_scanInt(), hour >= 0 && hour < 24 && nil != scanner.fhir_scanString(":"),
let minute = scanner.fhir_scanInt(), minute >= 0 && minute < 60 {
let digitSet = CharacterSet.decimalDigits
var decimalSet = NSMutableCharacterSet.decimalDigits
decimalSet.insert(".")
if nil != scanner.fhir_scanString(":"), let secStr = scanner.fhir_scanCharacters(from: decimalSet as CharacterSet), let second = Double(secStr), second < 60.0 {
time = FHIRTime(hour: UInt8(hour), minute: UInt8(minute), second: second, secondsFromString: secStr)
}
else {
time = FHIRTime(hour: UInt8(hour), minute: UInt8(minute), second: nil)
}
// scan zone
if !scanner.fhir_isAtEnd {
if nil != scanner.fhir_scanString("Z") {
tz = TimeZone(abbreviation: "UTC")
tzString = "Z"
}
else if let tzSign = (scanner.fhir_scanString("-") ?? scanner.fhir_scanString("+")) {
if let hourStr = scanner.fhir_scanCharacters(from: digitSet) {
var tzHrMin = hourStr
var tzhour = 0
var tzmin = 0
if 2 == hourStr.count {
tzhour = Int(hourStr) ?? 0
if nil != scanner.fhir_scanString(":"), let tzm = scanner.fhir_scanInt() {
tzHrMin += (tzm < 10) ? ":0\(tzm)" : ":\(tzm)"
if tzm < 60 {
tzmin = tzm
}
}
}
else if 4 == hourStr.count {
tzhour = Int(hourStr.substring(to: hourStr.index(hourStr.startIndex, offsetBy: 2)))!
tzmin = Int(hourStr.substring(from: hourStr.index(hourStr.startIndex, offsetBy: 2)))!
}
let offset = tzhour * 3600 + tzmin * 60
tz = TimeZone(secondsFromGMT: "+" == tzSign ? offset : -1 * offset)
tzString = tzSign + tzHrMin
}
}
}
}
}
return DT(date: date, time: time, tz: tz, tzString: tzString)
}
}
// MARK: -
/**
Extend Date to be able to return DateAndTime instances.
*/
public extension Date {
/** Create a `FHIRDate` instance from the receiver. */
func fhir_asDate() -> FHIRDate {
let (date, _, _) = DateNSDateConverter.shared.parse(date: self)
return date
}
/** Create a `Time` instance from the receiver. */
func fhir_asTime() -> FHIRTime {
let (_, time, _) = DateNSDateConverter.shared.parse(date: self)
return time
}
/** Create a `DateTime` instance from the receiver. */
func fhir_asDateTime() -> DateTime {
let (date, time, tz) = DateNSDateConverter.shared.parse(date: self)
return DateTime(date: date, time: time, timeZone: tz)
}
/** Create an `Instance` instance from the receiver. */
func fhir_asInstant() -> Instant {
let (date, time, tz) = DateNSDateConverter.shared.parse(date: self)
return Instant(date: date, time: time, timeZone: tz)
}
}
/**
Extend TimeZone to report the offset in "+00:00" or "Z" (for UTC/GMT) format.
*/
extension TimeZone {
/**
Return the offset as a string string.
- returns: The offset as a string; uses "Z" if the timezone is UTC or GMT
*/
func offset() -> String {
if "UTC" == identifier || "GMT" == identifier {
return "Z"
}
let secsFromGMT = secondsFromGMT()
let hr = abs((secsFromGMT / 3600) - (secsFromGMT % 3600))
let min = abs((secsFromGMT % 3600) / 60)
return (secsFromGMT >= 0 ? "+" : "-") + String(format: "%02d:%02d", hr, min)
}
}
/**
Extend Scanner to account for interface differences between macOS and Linux (as of November 2016)
*/
extension Scanner {
public var fhir_isAtEnd: Bool {
#if os(Linux)
return isAtEnd
#else
return isAtEnd
#endif
}
public func fhir_scanString(_ searchString: String) -> String? {
#if os(Linux)
var buffer: String?
_ = scanString(searchString, into: &buffer)
return buffer
#else
var str: NSString?
if scanString(searchString, into: &str) {
return str as String?
}
return nil
#endif
}
public func fhir_scanCharacters(from set: CharacterSet) -> String? {
#if os(Linux)
return scanCharactersFromSet(set)
#else
var str: NSString?
if scanCharacters(from: set, into: &str) {
return str as String?
}
return nil
#endif
}
public func fhir_scanInt() -> Int? {
var int = 0
#if os(Linux)
let flag = scanInt(&int)