diff --git a/DB/Sources/DB/Content/ContentDatabaseJSONEncoder.swift b/DB/Sources/DB/Content/ContentDatabaseJSONEncoder.swift index 28d7907..eba6158 100644 --- a/DB/Sources/DB/Content/ContentDatabaseJSONEncoder.swift +++ b/DB/Sources/DB/Content/ContentDatabaseJSONEncoder.swift @@ -7,11 +7,12 @@ final class ContentDatabaseJSONEncoder: JSONEncoder { override init() { super.init() - let dateFormatter = DateFormatter() - - dateFormatter.dateFormat = Constants.dateFormat - dateEncodingStrategy = .formatted(dateFormatter) keyEncodingStrategy = .convertToSnakeCase outputFormatting = .sortedKeys + dateEncodingStrategy = .custom { date, encoder in + var container = encoder.singleValueContainer() + + try container.encode(MastodonDecoder.dateFormatter.string(from: date)) + } } } diff --git a/Mastodon/Sources/Mastodon/Coding/MastodonDecoder.swift b/Mastodon/Sources/Mastodon/Coding/MastodonDecoder.swift index 3ff3d9a..78737d9 100644 --- a/Mastodon/Sources/Mastodon/Coding/MastodonDecoder.swift +++ b/Mastodon/Sources/Mastodon/Coding/MastodonDecoder.swift @@ -6,10 +6,26 @@ public final class MastodonDecoder: JSONDecoder { public override init() { super.init() - let dateFormatter = DateFormatter() - - dateFormatter.dateFormat = Constants.dateFormat - dateDecodingStrategy = .formatted(dateFormatter) 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 + }() +} diff --git a/Mastodon/Sources/Mastodon/Constants.swift b/Mastodon/Sources/Mastodon/Constants.swift deleted file mode 100644 index 7123cb0..0000000 --- a/Mastodon/Sources/Mastodon/Constants.swift +++ /dev/null @@ -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" -}