Created
October 3, 2016 18:56
-
-
Save Busta117/3fda59ce06f95241ed9899254d9ab831 to your computer and use it in GitHub Desktop.
objectmapper ISO8601 date transform
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 ObjectMapper | |
import RealmSwift | |
open class BaristaISO8601DateTransform: TransformType { | |
public typealias Object = Date | |
public typealias JSON = String | |
let dateFormatter: DateFormatter = DateFormatter() | |
public init() { | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" | |
} | |
private func check(withFormat format:String, string dateStr:String)-> Date? { | |
self.dateFormatter.dateFormat = format | |
return self.dateFormatter.date(from:dateStr) | |
} | |
open func transformFromJSON(_ value: Any?) -> Date? { | |
if let dateString = value as? String { | |
if let date = check(withFormat: "yyyy-MM-dd'T'HH:mm:ss'Z'", string: dateString) { | |
return date | |
}else if let date = check(withFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", string: dateString) { | |
return date | |
}else if let date = check(withFormat: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", string: dateString) { | |
return date | |
} | |
} | |
return nil | |
} | |
open func transformToJSON(_ value: Date?) -> String? { | |
if let date = value { | |
return dateFormatter.string(from: date) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment