Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Date conversion error #248

Closed
kiliankoe opened this issue Oct 19, 2015 · 3 comments
Closed

Date conversion error #248

kiliankoe opened this issue Oct 19, 2015 · 3 comments

Comments

@kiliankoe
Copy link
Contributor

Hi,

I've spent the day having lots of fun migrating a project of mine to use ObjectMapper. This really is a fantastic library!

I'm running into a little issue though. The API my app is talking to returns a few date strings. All of these are in UTC (for example: 2015-10-19T21:51:35). One example where I'm mapping them looks like this:

mutating func mapping(map: Map) {
  lastUpdated <- (map["last_updated"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss"))
}

This is then converted into the local value 2015-10-19 19:51:35 UTC by ObjectMapper, which would be correct according to my timezone (GMT+2) if the date from the API were not already in UTC. But since it is, it shouldn't be sent back two hours into the past.

Is there something obvious I'm missing here? Thanks for any help in advance! :)

@tristanhimmelman
Copy link
Owner

Hi @kiliankoe, I'm not exactly sure why the date is parsed incorrectly. CustomDateFormatTransform simply uses the following NSDateFormatter to convert date strings

let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = formatString

where formatString is the string you pass in above.

If you have a NSDateFormatter that object that handles your conversion properly, I recommend you use DateFormatterTransform instead, as it is initialized with a NSDateFormatter object.

@kiliankoe
Copy link
Contributor Author

Since I'm looking to decode a date that's not in the device's local timezone, it's probably my fault for not using the sensible default correctly. I failed to see that DateFormatterTransform even existed, that's a good idea, thanks!

I worked around the issue by using my own transformer:

let UTCDateFormatter = NSDateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss", timezone: NSTimeZone(name: "UTC")!)

let UTCTransform = TransformOf<NSDate, String>(fromJSON: {
    return UTCDateFormatter.dateFromString($0!)
}, toJSON: {
    return UTCDateFormatter.stringFromDate($0!)
})

If you think I'm right about the fault here being mine, feel free to close this issue.

@tristanhimmelman
Copy link
Owner

Glad you sorted something up 👍. A custom transform is perfectly good approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants