Created
June 9, 2017 02:58
-
-
Save takasek/f63512fd1b7a09403eef0c7063aeb47b to your computer and use it in GitHub Desktop.
JSONDecorderは、プロパティdateDecodingStrategyをsetすると、dateのパース方法を色々カスタマイズできるみたい #CodePiece
This file contains hidden or 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
import Foundation | |
struct S1: Codable { | |
let dateFromTimeInterval: Date | |
} | |
struct S2: Codable { | |
let dateFromISO8601: Date | |
} | |
struct S3: Codable { | |
let dateFromCustomFormat: Date | |
} | |
let data = """ | |
{ | |
"dateFromTimeInterval": 540000000, | |
"dateFromISO8601": "2017-01-01T12:34:56Z", | |
"dateFromCustomFormat": "2034ねん03がつ04にち05じ06ふん07びょう", | |
} | |
""".data(using: .utf8)! | |
do { | |
do { | |
let decoder = JSONDecoder() | |
let t = try decoder.decode(S1.self, from: data) | |
print(t) | |
} | |
do { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .iso8601 | |
let t = try decoder.decode(S2.self, from: data) | |
print(t) | |
} | |
do { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .formatted({ | |
let f = DateFormatter() | |
f.calendar = Calendar(identifier: .gregorian) | |
f.locale = .current | |
f.dateFormat = "yyyyねんMMがつddにちHHじmmふんssびょう" | |
return f | |
}()) | |
let t = try decoder.decode(S3.self, from: data) | |
print(t) | |
} | |
do { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .custom { | |
let container = try $0.singleValueContainer() | |
let str = try container.decode(String.self) | |
let f = DateFormatter() | |
f.calendar = Calendar(identifier: .gregorian) | |
f.locale = .current | |
f.dateFormat = "yyyyねんMMがつddにちHHじmmふんssびょう" | |
return f.date(from: str)! | |
} | |
let t = try decoder.decode(S3.self, from: data) | |
print(t) | |
} | |
} catch { | |
print(error) | |
} | |
/* 結果 | |
S1(dateFromTimeInterval: 2018-02-11 00:00:00 +0000) | |
S2(dateFromISO8601: 2017-01-01 12:34:56 +0000) | |
S3(dateFromCustomFormat: 2034-03-04 13:06:07 +0000) | |
S3(dateFromCustomFormat: 2034-03-04 13:06:07 +0000) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment