Created
April 5, 2016 07:11
-
-
Save floriankrueger/9e69cbe33706e6bd016ebe0cee2fe175 to your computer and use it in GitHub Desktop.
Decoding NSDate using Himotoki before 2.0 (-beta)
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
import Foundation | |
import Himotoki | |
enum ISO8601DateError: ErrorType { | |
case WrongFormat(string: String) | |
} | |
private let iso8601DateFormatter = NSDate.createIso8601DateFormatter() | |
extension NSDate: Decodable { | |
public static func decode(e: Extractor) throws -> NSDate { | |
if let string = e.rawValue as? String { | |
return try NSDate.dateFromIso8601String(string) | |
} else { | |
throw DecodeError.TypeMismatch(expected: "String", actual: e.description, keyPath: "date") | |
} | |
} | |
private static func createIso8601DateFormatter() -> NSDateFormatter { | |
let formatter = NSDateFormatter() | |
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ" | |
return formatter | |
} | |
private static func dateFromIso8601String(iso8601String: String) throws -> NSDate { | |
if let date = iso8601DateFormatter.dateFromString(iso8601String) { | |
return date | |
} | |
throw ISO8601DateError.WrongFormat(string: iso8601String) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment