|
| 1 | +import Foundation |
| 2 | + |
| 3 | +extension Date { |
| 4 | + @usableFromInline |
| 5 | + var iso8601String: String { |
| 6 | + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { |
| 7 | + return formatted(.iso8601.currentTimestamp(includingFractionalSeconds: true)) |
| 8 | + } else { |
| 9 | + return DateFormatter.iso8601(includingFractionalSeconds: true).string(from: self) |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + @usableFromInline |
| 14 | + init(iso8601String: String) throws { |
| 15 | + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { |
| 16 | + do { |
| 17 | + try self.init( |
| 18 | + iso8601String.queryOutput, |
| 19 | + strategy: .iso8601.currentTimestamp(includingFractionalSeconds: true) |
| 20 | + ) |
| 21 | + } catch { |
| 22 | + try self.init( |
| 23 | + iso8601String.queryOutput, |
| 24 | + strategy: .iso8601.currentTimestamp(includingFractionalSeconds: false) |
| 25 | + ) |
| 26 | + } |
| 27 | + } else { |
| 28 | + guard |
| 29 | + let date = DateFormatter.iso8601(includingFractionalSeconds: true).date(from: iso8601String) |
| 30 | + ?? DateFormatter.iso8601(includingFractionalSeconds: false).date(from: iso8601String) |
| 31 | + else { |
| 32 | + struct InvalidDate: Error { let string: String } |
| 33 | + throw InvalidDate(string: iso8601String) |
| 34 | + } |
| 35 | + self = date |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +extension DateFormatter { |
| 41 | + fileprivate static func iso8601(includingFractionalSeconds: Bool) -> DateFormatter { |
| 42 | + includingFractionalSeconds ? iso8601Fractional : iso8601Whole |
| 43 | + } |
| 44 | + |
| 45 | + fileprivate static let iso8601Fractional: DateFormatter = { |
| 46 | + let formatter = DateFormatter() |
| 47 | + formatter.calendar = Calendar(identifier: .iso8601) |
| 48 | + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" |
| 49 | + formatter.locale = Locale(identifier: "en_US_POSIX") |
| 50 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) |
| 51 | + return formatter |
| 52 | + }() |
| 53 | + |
| 54 | + fileprivate static let iso8601Whole: DateFormatter = { |
| 55 | + let formatter = DateFormatter() |
| 56 | + formatter.calendar = Calendar(identifier: .iso8601) |
| 57 | + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" |
| 58 | + formatter.locale = Locale(identifier: "en_US_POSIX") |
| 59 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) |
| 60 | + return formatter |
| 61 | + }() |
| 62 | +} |
| 63 | + |
| 64 | +@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) |
| 65 | +extension Date.ISO8601FormatStyle { |
| 66 | + fileprivate func currentTimestamp(includingFractionalSeconds: Bool) -> Self { |
| 67 | + year().month().day() |
| 68 | + .dateTimeSeparator(.space) |
| 69 | + .time(includingFractionalSeconds: includingFractionalSeconds) |
| 70 | + } |
| 71 | +} |
0 commit comments