-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathNaiveDate.swift
330 lines (267 loc) · 12.5 KB
/
NaiveDate.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
import Foundation
// MARK: - NaiveDate
/// Calendar date without a timezone.
public struct NaiveDate: Equatable, Hashable, Comparable, LosslessStringConvertible, Codable, _DateComponentsConvertible {
public let year: Int, month: Int, day: Int
enum CodingKeys: String, CodingKey {
case year
case month
case day
}
/// Initializes the naive date with a given date components.
/// - important: The naive types don't validate input components. For any
/// precise manipulations with time use native `Date` and `Calendar` types.
public init(year: Int, month: Int, day: Int) {
self.year = year; self.month = month; self.day = day
}
// MARK: Comparable
public static func <(lhs: NaiveDate, rhs: NaiveDate) -> Bool {
return (lhs.year, lhs.month, lhs.day) < (rhs.year, rhs.month, rhs.day)
}
// MARK: LosslessStringConvertible
/// Creates a naive date from a given string (e.g. "2017-12-30").
public init?(_ string: String) {
// Not using `ISO8601DateFormatter` because it only works with `Date`
guard let cmps = _components(from: string, separator: "-"), cmps.count == 3 else { return nil }
self = NaiveDate(year: cmps[0], month: cmps[1], day: cmps[2])
}
/// Returns a string representation of a naive date (e.g. "2017-12-30").
public var description: String {
return String(format: "%i-%.2i-%.2i", year, month, day)
}
// MARK: Codable
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self),
let year = try? container.decodeIfPresent(Int.self, forKey: .year),
let month = try? container.decodeIfPresent(Int.self, forKey: .month),
let day = try? container.decodeIfPresent(Int.self, forKey: .day) {
self.year = year
self.month = month
self.day = day
} else {
self = try _decode(from: decoder)
}
}
public func encode(to encoder: Encoder) throws {
if String(describing: encoder) == "SwiftData.CompositeEncoder" {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(year, forKey: .year)
try container.encode(month, forKey: .month)
try container.encode(day, forKey: .day)
} else {
try _encode(self, to: encoder)
}
}
// MARK: _DateComponentsConvertible
public var dateComponents: DateComponents {
return DateComponents(year: year, month: month, day: day)
}
}
// MARK: - NaiveTime
/// Time without a timezone. Allows for second precision.
public struct NaiveTime: Equatable, Hashable, Comparable, LosslessStringConvertible, Codable, _DateComponentsConvertible {
public let hour: Int, minute: Int, second: Int
enum CodingKeys: String, CodingKey {
case hour
case minute
case second
}
/// Initializes the naive time with a given date components.
/// - important: The naive types don't validate input components. For any
/// precise manipulations with time use native `Date` and `Calendar` types.
public init(hour: Int = 0, minute: Int = 0, second: Int = 0) {
self.hour = hour; self.minute = minute; self.second = second
}
/// Initializes a naive time with a given time interval. E.g.
/// `NaiveTime(timeInterval: 3610)` returns `NaiveTime(hour: 1, second: 10)`.
public init(timeInterval ti: Int) {
self = NaiveTime(hour: ti / 3600, minute: (ti / 60) % 60, second: ti % 60)
}
/// Returns a total number of seconds. E.g.
/// `NaiveTime(hour: 1, second: 10).timeInterval` returns `3610`.
public var timeInterval: Int {
return hour * 3600 + minute * 60 + second
}
// MARK: Comparable
public static func <(lhs: NaiveTime, rhs: NaiveTime) -> Bool {
return (lhs.hour, lhs.minute, lhs.second) < (rhs.hour, rhs.minute, rhs.second)
}
// MARK: LosslessStringConvertible
/// Creates a naive time from a given string (e.g. "23:59", or "23:59:59").
public init?(_ string: String) {
guard let cmps = _components(from: string, separator: ":"),
(2...3).contains(cmps.count) else { return nil }
self.init(hour: cmps[0], minute: cmps[1], second: (cmps.count > 2 ? cmps[2] : 0))
}
/// Returns a string representation of a naive time (e.g. "23:59:59").
public var description: String {
return String(format: "%.2i:%.2i:%.2i", hour, minute, second)
}
// MARK: Codable
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self),
let hour = try? container.decodeIfPresent(Int.self, forKey: .hour),
let minute = try? container.decodeIfPresent(Int.self, forKey: .minute),
let second = try? container.decodeIfPresent(Int.self, forKey: .second) {
self.hour = hour
self.minute = minute
self.second = second
} else {
self = try _decode(from: decoder)
}
}
public func encode(to encoder: Encoder) throws {
if String(describing: encoder) == "SwiftData.CompositeEncoder" {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(hour, forKey: .hour)
try container.encode(minute, forKey: .minute)
try container.encode(second, forKey: .second)
} else {
try _encode(self, to: encoder)
}
}
// MARK: _DateComponentsConvertible
public var dateComponents: DateComponents {
return DateComponents(hour: hour, minute: minute, second: second)
}
}
// MARK: - NaiveDateTime
/// Combined date and time without timezone.
public struct NaiveDateTime: Equatable, Hashable, Comparable, LosslessStringConvertible, Codable, _DateComponentsConvertible {
public let date: NaiveDate
public let time: NaiveTime
enum CodingKeys: String, CodingKey {
case date
case time
}
/// Initializes the naive datetime with a given date components.
/// - important: The naive types don't validate input components. For any
/// precise manipulations with time use native `Date` and `Calendar` types.
public init(date: NaiveDate, time: NaiveTime) {
self.date = date; self.time = time
}
/// Initializes the naive datetime with a given date components.
/// - important: The naive types don't validate input components. For any
/// precise manipulations with time use native `Date` and `Calendar` types.
public init(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
self.date = NaiveDate(year: year, month: month, day: day)
self.time = NaiveTime(hour: hour, minute: minute, second: second)
}
// MARK: Comparable
public static func <(lhs: NaiveDateTime, rhs: NaiveDateTime) -> Bool {
if lhs.date != rhs.date { return lhs.date < rhs.date }
return lhs.time < rhs.time
}
// MARK: LosslessStringConvertible
/// Creates a naive datetime from a given string (e.g. "2017-12-30T23:59:59").
public init?(_ string: String) {
let components = string.components(separatedBy: "T")
guard components.count == 2 else { return nil } // must have both date & time
guard let date = NaiveDate(components[0]), let time = NaiveTime(components[1]) else { return nil }
self = NaiveDateTime(date: date, time: time)
}
/// Returns a string representation of a naive datetime (e.g. "2017-12-30T23:59:59").
public var description: String {
return "\(date)T\(time)"
}
// MARK: Codable
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self),
let date = try? container.decodeIfPresent(NaiveDate.self, forKey: .date),
let time = try? container.decodeIfPresent(NaiveTime.self, forKey: .time) {
self.date = date
self.time = time
} else {
self = try _decode(from: decoder)
}
}
public func encode(to encoder: Encoder) throws {
if encoder.isSwiftDataComposite {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(date, forKey: .date)
try container.encode(time, forKey: .time)
} else {
try _encode(self, to: encoder)
}
}
// MARK: _DateComponentsConvertible
public var dateComponents: DateComponents {
return DateComponents(year: date.year, month: date.month, day: date.day, hour: time.hour, minute: time.minute, second: time.second)
}
}
// MARK: - Calendar Extensions
public extension Calendar {
// MARK: Naive* -> Date
/// Returns a date in calendar's time zone created from the naive date.
func date(from date: NaiveDate, in timeZone: TimeZone? = nil) -> Date? {
return _date(from: date, in: timeZone)
}
/// Returns a date in calendar's time zone created from the naive time.
func date(from time: NaiveTime, in timeZone: TimeZone? = nil) -> Date? {
return _date(from: time, in: timeZone)
}
/// Returns a date in calendar's time zone created from the naive datetime.
func date(from dateTime: NaiveDateTime, in timeZone: TimeZone? = nil) -> Date? {
return _date(from: dateTime, in: timeZone)
}
internal func _date<T: _DateComponentsConvertible>(from value: T, in timeZone: TimeZone? = nil) -> Date? {
var components = value.dateComponents
components.timeZone = timeZone
return self.date(from: components)
}
// MARK: Date -> Naive*
/// Returns naive date from a date, as if in a given time zone. User calendar's time zone.
/// - parameter timeZone: By default uses calendar's time zone.
func naiveDate(from date: Date, in timeZone: TimeZone? = nil) -> NaiveDate {
let components = self.dateComponents(in: timeZone ?? self.timeZone, from: date)
return NaiveDate(year: components.year!, month: components.month!, day: components.day!)
}
/// Returns naive time from a date, as if in a given time zone. User calendar's time zone.
/// - parameter timeZone: By default uses calendar's time zone.
func naiveTime(from date: Date, in timeZone: TimeZone? = nil) -> NaiveTime {
let components = self.dateComponents(in: timeZone ?? self.timeZone, from: date)
return NaiveTime(hour: components.hour!, minute: components.minute!, second: components.second!)
}
/// Returns naive time from a date, as if in a given time zone. User calendar's time zone.
/// - parameter timeZone: By default uses calendar's time zone.
func naiveDateTime(from date: Date, in timeZone: TimeZone? = nil) -> NaiveDateTime {
let components = self.dateComponents(in: timeZone ?? self.timeZone, from: date)
return NaiveDateTime(
date: NaiveDate(year: components.year!, month: components.month!, day: components.day!),
time: NaiveTime(hour: components.hour!, minute: components.minute!, second: components.second!)
)
}
}
// MARK: - Private
/// A type that can be converted to DateComponents (and in turn to Date).
internal protocol _DateComponentsConvertible {
var dateComponents: DateComponents { get }
}
private func _decode<T: LosslessStringConvertible>(from decoder: Decoder) throws -> T {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
guard let value = T(string) else {
throw Swift.DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid string format: \(string)")
}
return value
}
private func _encode<T: LosslessStringConvertible>(_ value: T, to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value.description)
}
private func _components(from string: String, separator: String) -> [Int]? {
let substrings = string.components(separatedBy: separator)
let components = substrings.compactMap(Int.init)
return components.count == substrings.count ? components : nil
}
extension Encoder {
/// SwiftData composite encoder can't accept single value
/// as it expects to code each of attributes under the hood, which will match internal .compositeDescription
/// Otherwise null/zero data will be saved.
///
/// So we detect it like this for now.
var isSwiftDataComposite: Bool {
// TODO: Figure out other way instead of introspection
String(describing: self) == "SwiftData.CompositeEncoder"
}
}