【问题标题】:Swift Object Mapper passing a different dateSwift Object Mapper 传递不同的日期
【发布时间】:2018-07-06 19:19:37
【问题描述】:

我正在使用 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"

谢谢!

【问题讨论】:

    标签: ios json swift alamofire objectmapper


    【解决方案1】:

    尝试改用DateFormatterTransform

    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

    【讨论】:

    • 非常感谢!
    • 它将日期值更改为 "String" ,而不是 Date() 了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多