-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTime.swift
More file actions
275 lines (247 loc) · 9.2 KB
/
DateTime.swift
File metadata and controls
275 lines (247 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import Foundation
/// DateTime is an ISO 8601 timestamp paired with a timezone name. Haystack requires all timestamps
/// to include a timezone. Timezone names are standardized in the
/// [timezone database](https://project-haystack.org/doc/docHaystack/TimeZones)
/// (city name from zoneinfo database). Implementations should support DateTime precision at least
/// down to the millisecond.
///
/// [Docs](https://project-haystack.org/doc/docHaystack/Kinds#datetime)
public struct DateTime: Val {
public static var valType: ValType { .DateTime }
public static let utcName = "UTC"
public let date: Foundation.Date
public let gmtOffset: Int
public let timezone: String
public init(date: Foundation.Date) {
self.date = date
gmtOffset = 0
timezone = Self.utcName
}
public init(
year: Int,
month: Int,
day: Int,
hour: Int = 0,
minute: Int = 0,
second: Int = 0,
millisecond: Int = 0,
gmtOffset: Int = 0,
timezone: String = Self.utcName
) throws {
let components = DateComponents(
calendar: calendar,
timeZone: .init(secondsFromGMT: gmtOffset),
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
nanosecond: millisecond * 1_000_000
)
guard let date = components.date else {
throw ValError.invalidDateTimeDefinition
}
self.date = date
self.gmtOffset = gmtOffset
self.timezone = timezone
}
public init(
date: Date,
time: Time,
gmtOffset: Int = 0,
timezone: String = Self.utcName
) throws {
let components = DateComponents(
calendar: calendar,
timeZone: .init(secondsFromGMT: gmtOffset),
year: date.year,
month: date.month,
day: date.day,
hour: time.hour,
minute: time.minute,
second: time.second,
nanosecond: time.millisecond * 1_000_000
)
guard let date = components.date else {
throw ValError.invalidDateTimeDefinition
}
self.date = date
self.gmtOffset = gmtOffset
self.timezone = timezone
}
public init(_ string: String) throws {
let splits = string.split(separator: " ")
let isoString = String(splits[0])
let (date, gmtOffset) = try Self.dateFromString(isoString)
self.date = date
self.gmtOffset = gmtOffset
if splits.count > 1 {
timezone = String(splits[1])
} else {
timezone = Self.utcName
}
}
/// Converts to Zinc formatted string.
/// See [Zinc Literals](https://project-haystack.org/doc/docHaystack/Zinc#literals)
public func toZinc() -> String {
var zinc: String
if hasMilliseconds {
zinc = dateTimeWithMillisFormatter.string(from: date)
} else {
zinc = dateTimeFormatter.string(from: date)
}
if timezone != Self.utcName {
zinc += " \(timezone)"
}
return zinc
}
static func dateFromString(_ isoString: String) throws -> (Foundation.Date, Int) {
// Must use Regex so we can preserve GMT offset details. dateFormatter doesn't give us this
let expr = try NSRegularExpression(pattern: #"(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2}\.?\d*)([+-]\d{2}:\d{2}|Z)"#)
guard let match = expr.firstMatch(
in: isoString,
range: NSRange(isoString.startIndex ..< isoString.endIndex, in: isoString)
) else {
throw ValError.invalidDateTimeFormat(isoString)
}
guard
let dateRange = Range(match.range(at: 1), in: isoString),
let timeRange = Range(match.range(at: 2), in: isoString),
let offsetRange = Range(match.range(at: 3), in: isoString)
else {
throw ValError.invalidDateTimeFormat(isoString)
}
let date = try Date(String(isoString[dateRange]))
let time = try Time(String(isoString[timeRange]))
let offsetStr = String(isoString[offsetRange])
let gmtOffset: Int
if offsetStr == "Z" {
gmtOffset = 0
} else {
let offsetExpr = try NSRegularExpression(pattern: #"([+-])(\d{2}):(\d{2})"#)
guard let offsetMatch = offsetExpr.firstMatch(
in: offsetStr,
range: NSRange(offsetStr.startIndex ..< offsetStr.endIndex, in: offsetStr)
) else {
throw ValError.invalidDateTimeFormat(isoString)
}
guard
let symbolRange = Range(offsetMatch.range(at: 1), in: offsetStr),
let hourRange = Range(offsetMatch.range(at: 2), in: offsetStr),
let minuteRange = Range(offsetMatch.range(at: 3), in: offsetStr),
let hour = Int(String(offsetStr[hourRange])),
let minute = Int(String(offsetStr[minuteRange]))
else {
throw ValError.invalidDateTimeFormat(isoString)
}
let sign = String(offsetStr[symbolRange]) == "+" ? 1 : -1
gmtOffset = sign * ((hour * 60 * 60) + (minute * 60))
}
let components = DateComponents(
calendar: calendar,
timeZone: .init(secondsFromGMT: gmtOffset),
year: date.year,
month: date.month,
day: date.day,
hour: time.hour,
minute: time.minute,
second: time.second,
nanosecond: time.millisecond * 1_000_000
)
guard let date = components.date else {
throw ValError.invalidDateTimeDefinition
}
return (date, gmtOffset)
}
private var hasMilliseconds: Bool {
return calendar.component(.nanosecond, from: date) != 0
}
/// Singleton Haystack DateTime formatter
var dateTimeFormatter: ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime]
formatter.timeZone = .init(secondsFromGMT: gmtOffset)
return formatter
}
/// Singleton Haystack DateTime formatter with fractional second support
var dateTimeWithMillisFormatter: ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
formatter.timeZone = .init(secondsFromGMT: gmtOffset)
return formatter
}
}
let calendar = Calendar(identifier: .gregorian)
// DateTime + Codable
extension DateTime {
static let kindValue = "dateTime"
enum CodingKeys: CodingKey {
case _kind
case val
case tz
}
/// Read from decodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#dateTime)
public init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: Self.CodingKeys.self) else {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [],
debugDescription: "Date representation must be an object"
)
)
}
guard try container.decode(String.self, forKey: ._kind) == Self.kindValue else {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [Self.CodingKeys._kind],
debugDescription: "Expected `_kind` to have value `\"\(Self.kindValue)\"`"
)
)
}
let isoString = try container.decode(String.self, forKey: .val)
do {
let (date, gmtOffset) = try Self.dateFromString(isoString)
self.date = date
self.gmtOffset = gmtOffset
} catch {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [Self.CodingKeys.val],
debugDescription: "DateTime value in incorrect format: `\"\(isoString)\"`"
)
)
}
let timezone = (try? container.decode(String.self, forKey: .tz)) ?? Self.utcName
self.timezone = timezone
}
/// Write to encodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#dateTime)
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Self.CodingKeys.self)
try container.encode(Self.kindValue, forKey: ._kind)
let isoString: String
if hasMilliseconds {
isoString = dateTimeWithMillisFormatter.string(from: date)
} else {
isoString = dateTimeFormatter.string(from: date)
}
try container.encode(isoString, forKey: .val)
if timezone != DateTime.utcName {
try container.encode(timezone, forKey: .tz)
}
}
}
// DateTime + Comparable
extension DateTime: Comparable {
public static func < (lhs: DateTime, rhs: DateTime) -> Bool {
return lhs.date < rhs.date
}
public static func == (lhs: DateTime, rhs: DateTime) -> Bool {
return lhs.date == rhs.date
}
}