Use system ISO8601DateFormatter

This commit is contained in:
Justin Mazzocchi 2021-03-12 18:27:07 -08:00
parent d11d644674
commit dae380bf6d
No known key found for this signature in database
GPG key ID: E223E6937AAFB01C
3 changed files with 25 additions and 15 deletions

View file

@ -7,11 +7,12 @@ final class ContentDatabaseJSONEncoder: JSONEncoder {
override init() { override init() {
super.init() super.init()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = Constants.dateFormat
dateEncodingStrategy = .formatted(dateFormatter)
keyEncodingStrategy = .convertToSnakeCase keyEncodingStrategy = .convertToSnakeCase
outputFormatting = .sortedKeys outputFormatting = .sortedKeys
dateEncodingStrategy = .custom { date, encoder in
var container = encoder.singleValueContainer()
try container.encode(MastodonDecoder.dateFormatter.string(from: date))
}
} }
} }

View file

@ -6,10 +6,26 @@ public final class MastodonDecoder: JSONDecoder {
public override init() { public override init() {
super.init() super.init()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = Constants.dateFormat
dateDecodingStrategy = .formatted(dateFormatter)
keyDecodingStrategy = .convertFromSnakeCase keyDecodingStrategy = .convertFromSnakeCase
dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
guard let date = Self.dateFormatter.date(from: dateString) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unable to parse ISO8601 date")
}
return date
}
} }
} }
public extension MastodonDecoder {
static let dateFormatter: ISO8601DateFormatter = {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return dateFormatter
}()
}

View file

@ -1,7 +0,0 @@
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
public enum Constants {
public static let dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
}