alickbass / SwiftyJSONModel

Better way to use SwiftyJSON with custom models
MIT License
29 stars 11 forks source link

No example for Dates in ReadMe #49

Open meurig opened 5 years ago

meurig commented 5 years ago

Hi, and thanks for the great library!

I'm pretty new to all this and trying to map a json result to a Date. I notice you've merged some code adding support for Dates (that's great!) but it would people like me if the documentation gave a brief example for how this works.

Many thanks,

Meurig

meurig commented 5 years ago

I've no idea if this is the best way to do it, but for reference I've ended up with:

timestamp = try object.value(for: .timestamp, with: DateFormatTransform())

Where DateFormatTransform is declared as:

public class DateFormatTransform: DateTransformer {
    public func date(from string: String) throws -> Date {
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        return dateformatter.date(from: string)!
    }

    public func string(form date: Date) -> String {
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        return dateformatter.string(from: date)
    }
}