Skip to content

Instantly share code, notes, and snippets.

@RodolfoAntonici
Created November 29, 2016 12:02
Show Gist options
  • Save RodolfoAntonici/2c446d829ddefc19afe0635ce2977d2d to your computer and use it in GitHub Desktop.
Save RodolfoAntonici/2c446d829ddefc19afe0635ce2977d2d to your computer and use it in GitHub Desktop.
//
// DateFormatTransform.swift
//
// Created by Rodolfo Antonici on 29/11/16.
// No copyright, just use it as it's.
// ObjectMapper version 2.2
//
// A simple class using the TransformType protocol of ObjectMapper to convert Date String into a NSDate object
import Foundation
import ObjectMapper
public class DateFormatTransform: TransformType {
public typealias Object = NSDate
public typealias JSON = String
var dateFormat = NSDateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss")
convenience init(dateFormat: String) {
self.init()
self.dateFormat = NSDateFormatter(dateFormat: dateFormat)
}
public func transformFromJSON(value: AnyObject?) -> Object? {
if let dateString = value as? String {
return self.dateFormat.dateFromString(dateString)
}
return nil
}
public func transformToJSON(value: NSDate?) -> JSON? {
if let date = value {
return self.dateFormat.stringFromDate(date)
}
return nil
}
}
// Sample Usage:
//class SomeObject: Mappable {
//
// var name: String?
// var categorizationDate: NSDate?
// var startDate: NSDate?
// var endDate: NSDate?
//
// required convenience init?(_ map: Map) {
// self.init()
// }
//
// Using the same object to multiple Date fields (performance benefits)
// override func mapping(map: Map) {
// super.mapping(map)
//
// let dateFormatTransformer = DateFormatTransform(dateFormat: "yyyy-MM-dd'T'HH:mm:ss")
//
// name <- map["name"]
// categorizationDate <- (map["categorization"], dateFormatTransformer)
// startDate <- (map["start"], dateFormatTransformer)
// endDate <- (map["end"], dateFormatTransformer)
// }
//
// A direct approach to a single format to each field or when there's a single field
// override func mapping(map: Map) {
// super.mapping(map)
//
// name <- map["name"]
// categorizationDate <- (map["categorization"], DateFormatTransform(dateFormat: "yyyy-MM-dd'T'HH:mm:ss"))
// startDate <- (map["start"], DateFormatTransform(dateFormat: "yyyy-MM-dd"))
// endDate <- (map["end"], DateFormatTransform(dateFormat: "HH:mm:ss"))
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment