Search code examples
iosjsonswiftalamofireobjectmapper

Swift Object Mapper passing a different date


I'm using ObjectMapper to get json into objects, but each time the date is set as 1970-01-01. I can't see what my issue is since I though DateTransform would be able to handle the format.

Here's the class:

import Foundation
import ObjectMapper

class example :Mappable
{
    var ExampleDate: Date?

    required init?(map: Map){
    }

    //Mappable
    func mapping(map: Map){
        ExampleDate          <- (map["ReviewDate"], DateTransform())
    }

}

This is how one of the dates looks:

ExampleDate = "2018-07-05T12:41:52.087+00:00"

Thank you!


Solution

  • Try using a DateFormatterTransform instead:

    import Foundation
    import ObjectMapper
    
    class example :Mappable
    {
        var ExampleDate: Date?
    
        required init?(map: Map){
        }
    
        //Mappable
        func mapping(map: Map){
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSZ"
            dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    
            ExampleDate <- (map["ReviewDate"], DateFormatterTransform(dateFormatter: dateFormatter))
        }
    }
    

    And as a general observation try do avoid using a capital first letter for your variable names. It's the recommended way so you can easily distinguish them from types. So use exampleDate instead of ExampleDate