Skip to content

Instantly share code, notes, and snippets.

@Busta117
Created October 3, 2016 18:56
Show Gist options
  • Save Busta117/3fda59ce06f95241ed9899254d9ab831 to your computer and use it in GitHub Desktop.
Save Busta117/3fda59ce06f95241ed9899254d9ab831 to your computer and use it in GitHub Desktop.
objectmapper ISO8601 date transform
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