-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDate+JSONSerialization.swift
More file actions
38 lines (33 loc) · 1.25 KB
/
Date+JSONSerialization.swift
File metadata and controls
38 lines (33 loc) · 1.25 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
import Foundation
extension Date: JSONSerializable {
public func toJSONObject() -> Any {
return JSONDateFormatter.string(from: self)
}
}
extension Date: JSONDeserializable {
public init(JSONObject: Any) throws {
guard let dateString = JSONObject as? String,
let date = JSONDateFormatter.date(from: dateString) else {
throw AutoJSONDeserializableError.typeMismatchError(String.self)
}
self = date
}
}
enum JSONDateFormatter {
static func date(from string: String) -> Date? {
// [HACK] workaround for unsupported milliseconds part in ISO8601DateFormatter.
// "1985-04-12T23:20:50Z" is supported where "1985-04-12T23:20:50.678Z" is not.
// So this removes the ".678" part.
let dateString = string.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
// [/HACK]
return isoDateFormatter.date(from: dateString)
}
static func string(from date: Date) -> String {
return isoDateFormatter.string(from: date)
}
private static let isoDateFormatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
}