4

The following code crashes in XCode 8 when running on iOS 10 (does not crash on previous iOS versions):

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.locale = NSLocale.currentLocale()


let date = dateFormatter.dateFromString("2016-09-04T08:32:46.195514289Z")!

The crash happens because the date formatter returns nil. I tried playing and changing the dateFormat but the result is always nil. Did something change in iOS 10?

EDIT: same code works in Storyboard when running with Swift 3. It seems that the issue happens with Swift 2.3 and iOS 10

Erik Sapir
  • 23,209
  • 28
  • 81
  • 141
  • 4
    Cannot reproduce. However, when working with fixed date formats, it is always a good idea to set the locale to "en_US_POSIX" and not to the current locale. That might solve your problem. – Martin R Sep 18 '16 at 14:49
  • 3
    With respect to the current answers: Please note that "it works for me" is not considered an acceptable answer, compare http://meta.stackoverflow.com/questions/277923/are-your-code-works-fine-for-me-answers-acceptable. – Martin R Sep 18 '16 at 14:56
  • 1
    Even with Swift 2.3 I cannot reproduce. Have you tried the POSIX locale? – Martin R Sep 18 '16 at 15:06
  • @MartinR Yep, setting locale to POSIX did the trick :). Thanks! – Erik Sapir Sep 18 '16 at 15:22
  • I also have this issue (with a single user on iOS 10.2) - how do I set the locale to POSIX? – diachedelic Jan 28 '17 at 09:27
  • This category seems to offer a solution: http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature – diachedelic Jan 28 '17 at 09:43

2 Answers2

1

Works for me. Although I am using Swift 3:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"
df.timeZone = TimeZone(abbreviation: "UTC")
df.locale = NSLocale.current
let date = df.date(from: "2016-09-04T08:32:46.195514289Z")
print("date: \(date)")

Prints:

date: Optional(2016-09-04 08:32:46 +0000)
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
0

I tested your code in a Playground (had to convert it to Swift 3 to do this) and it worked. But I noticed, that in Swift 3, the timeZone is initialized like this:

TimeZone(abbreviation: "UTC")

This initializer is also available in NSTimeZone, which you can use in Swift 2.x. According to Apple's documentation, this would be the correct initializer, when you use something like "UTC" or "GMT" as name. I'm not sure, what we are supposed to do with init(name:)

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
  • @MartinR I'm saying that it worked in Swift 3 and provided a possible solution for Swift 2.x. In my opinion, this is not simply saying: "it works for me" – FelixSFD Sep 18 '16 at 14:57