Why my code is working in playground but not in my project?

Hi,


I was playing with NSDateFormater to parse a string I am getting from a rest api, in a playground.

And it is working fine. Here the exact lines I have in my playground:

import UIKit
let lTs = String("Mon, 07 Dec 2015 3:58 pm EST")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy h:mm a zzz"
let lDate = dateFormatter.dateFromString(lTs)
print("\(lDate!)")


The result is "2015-12-07 20:58:00 +0000\n"


By if I copy-paste this code in my project, it crashes at the print line because the lDate variable is nil!!!

How is it possible?

This part of code is in a callback from an api call (using Alamofire)


I have absolutely no clue on why this is happening. Is there a way to see the reason why NSDateFormater is failing?


Thanks

Accepted Reply

I was playing with NSDateFormater to parse a string I am getting from a rest api …

If you’re parsing a fixed format date string, you need to force the locale to something fixed otherwise your parsing will fail mysterious depending on the user’s region configuration. QA1480 NSDateFormatter and Internet Dates shows the approach we recommend.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

It's probably because creating a new NSDateFormatter using the default initializer is preloading it with some kind of locale information only in the production app. Remember that because a playground is a different runtime environment than an app (especially an iOS app), code that uses the system libraries may behave slightly differently.

You might find this helpful: https://forums.developer.apple.com/thread/27726

I was playing with NSDateFormater to parse a string I am getting from a rest api …

If you’re parsing a fixed format date string, you need to force the locale to something fixed otherwise your parsing will fail mysterious depending on the user’s region configuration. QA1480 NSDateFormatter and Internet Dates shows the approach we recommend.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks for the responses!


Just adding the line:

dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

Fixed my problem!