Skip to content

Commit

Permalink
Change up the Codable implementation of GregorianDay to use an ISO st…
Browse files Browse the repository at this point in the history
…andard format
  • Loading branch information
Jeehut committed Feb 22, 2024
1 parent c63a6ed commit 4af6632
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion Sources/HandySwift/Types/GregorianDay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,33 @@ public struct GregorianDay {
}
}

extension GregorianDay: Codable, Hashable, Sendable {}
extension GregorianDay: Codable {
static var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.calendar = Calendar(identifier: .gregorian)
return dateFormatter
}

public init(from decoder: Decoder) throws {
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: "Cannot decode date string")
}

self = GregorianDay(date: date)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let dateString = Self.dateFormatter.string(from: self.startOfDay())
try container.encode(dateString)
}
}

extension GregorianDay: Hashable, Sendable {}
extension GregorianDay: Identifiable {
public var id: String { "\(self.year)-\(self.month)-\(self.day)" }
}
Expand Down

0 comments on commit 4af6632

Please sign in to comment.