Skip to content

Instantly share code, notes, and snippets.

@kopyl
Created February 2, 2026 17:39
Show Gist options
  • Select an option

  • Save kopyl/a0610b872f9456e0188a9bb08aa7f218 to your computer and use it in GitHub Desktop.

Select an option

Save kopyl/a0610b872f9456e0188a9bb08aa7f218 to your computer and use it in GitHub Desktop.
import Foundation
struct Record: Codable {
let id: String
let updatedAt: Date
}
// Create a date with fractional seconds
let now = Date()
let record = Record(id: "test-123", updatedAt: now)
print("Original date: \(now)")
print("TimeInterval: \(now.timeIntervalSince1970)")
print()
// === Strategy 1: Standard .iso8601 (NO fractional seconds) ===
print("=== Strategy 1: .iso8601 (default, no fractions) ===")
let encoder1 = JSONEncoder()
encoder1.dateEncodingStrategy = .iso8601
encoder1.outputFormatting = .prettyPrinted
let decoder1 = JSONDecoder()
decoder1.dateDecodingStrategy = .iso8601
let json1 = try! encoder1.encode(record)
print("Encoded JSON:")
print(String(data: json1, encoding: .utf8)!)
let decoded1 = try! decoder1.decode(Record.self, from: json1)
print("\nDecoded date: \(decoded1.updatedAt)")
print("TimeInterval: \(decoded1.updatedAt.timeIntervalSince1970)")
print()
// === Strategy 2: Custom with fractional seconds ===
print("=== Strategy 2: Custom with fractional seconds ===")
let iso8601WithFractionalSeconds: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
let encoder2 = JSONEncoder()
encoder2.outputFormatting = .prettyPrinted
encoder2.dateEncodingStrategy = .custom { date, encoder in
var container = encoder.singleValueContainer()
let string = iso8601WithFractionalSeconds.string(from: date)
try container.encode(string)
}
let decoder2 = JSONDecoder()
decoder2.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = iso8601WithFractionalSeconds.date(from: string) {
return date
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
}
let json2 = try! encoder2.encode(record)
print("Encoded JSON:")
print(String(data: json2, encoding: .utf8)!)
let decoded2 = try! decoder2.decode(Record.self, from: json2)
print("\nDecoded date: \(decoded2.updatedAt)")
print("TimeInterval: \(decoded2.updatedAt.timeIntervalSince1970)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment