I have created the following, simple Swift function to convert a String into a Date
object. However, the dateFormatter
always returns nil
, even on valid inputs like 2020-02-27
func date(fromString str: String?) -> Date? {
if let dateStr = str {
if dateStr.count == 0 {
return nil
}
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let result = dateFormatter.date(from: dateStr) // --> nil
//let result = dateFormatter.date(from: "2020-02-27") // --> nil as well
return result
}
This is (more or less) a ported version some Objectiv-C code where everything works fine.
How to fix this?
UPDATE:
As mentioned in the comments the problem does NOT show when I execute the code in Swift Playground. It seems that this is some wired problem with Xcode and the simulator. I will re-check this!