首页 > 解决方案 > Swift Object Mapper 传递不同的日期

问题描述

我正在使用 ObjectMapper 将 json 转换为对象,但每次将日期设置为 1970-01-01。我看不出我的问题是什么,因为我虽然 DateTransform 能够处理格式。

这是课程:

import Foundation
import ObjectMapper

class example :Mappable
{
    var ExampleDate: Date?

    required init?(map: Map){
    }

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

}

这是其中一个日期的外观:

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

谢谢!

标签: iosjsonswiftalamofireobjectmapper

解决方案


尝试使用 aDateFormatterTransform代替:

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))
    }
}

作为一般观察,请尽量避免在变量名中使用大写的首字母。这是推荐的方式,因此您可以轻松地将它们与类型区分开来。所以使用exampleDate而不是ExampleDate


推荐阅读