AntonSack
AntonSack

Reputation: 1051

Swift: Result of dateFromString nil unexpectely

I went through all related questions and tried all suggestions but it just didn't worked out for me:

 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
 dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
 dateFormatter.dateStyle = .FullStyle
 let timestamp = dateFormatter.dateFromString("07.07.2015 19:07")

timestamp is nil.... :-(

Upvotes: 1

Views: 92

Answers (1)

Eric Aya
Eric Aya

Reputation: 70097

Remove the line with the NSDateFormatterStyle:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let timestamp = dateFormatter.dateFromString("07.07.2015 19:07")

This is because setting an NSDateFormatterStyle overrides dateFormatter.dateFormat, making the results nil when using both.

The solution is to not use NSDateFormatterStyle if you already have a dateFormat.

Upvotes: 2

Related Questions