-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
578c450
commit 8bf533c
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
MemoryChainKit/Sources/Extensions/Foudantion/JSONDecoderExtension.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// | ||
// JSONDecoderExtension.swift | ||
// MemoryChainKit | ||
// | ||
// Created by Marc Steven on 2023/11/11. | ||
// Copyright © 2023 Marc Steven(https://marcsteven.top). All rights reserved. | ||
// | ||
|
||
import Foundation | ||
|
||
|
||
public extension JSONDecoder.DateDecodingStrategy { | ||
|
||
enum DateFormat: String, CaseIterable { | ||
case noTime = "yyyy-mm-dd" | ||
case dateWithTime = "yyyy-MM-dd HH:mm:ss" | ||
case iso8601 = "yyyy-MM-dd'T'HH:mm:ssZ" | ||
case iso8601WithMilliseconds = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" | ||
|
||
var formatter: DateFormatter { | ||
let dateFormatter = DateFormatter() | ||
dateFormatter.dateFormat = rawValue | ||
return dateFormatter | ||
} | ||
} | ||
|
||
static var supportMultipleDateFormats: JSONDecoder.DateDecodingStrategy { | ||
return JSONDecoder.DateDecodingStrategy.custom({ (decoder) -> Date in | ||
let container = try decoder.singleValueContainer() | ||
let dateStr = try container.decode(String.self) | ||
|
||
var date: Date? | ||
|
||
for format in DateFormat.allCases { | ||
date = format.formatter.date(from: dateStr) | ||
if date != nil { | ||
break | ||
} | ||
} | ||
|
||
guard let calculatedDate = date else { | ||
throw DecodingError.dataCorruptedError( | ||
in: container, | ||
debugDescription: "Cannot decode date string \(dateStr)" | ||
) | ||
} | ||
|
||
return calculatedDate | ||
}) | ||
} | ||
} |