Search code examples
iosswiftdateformatter

Proper construction of dateFormat to parse time using DateFormatter in Swift 3.1


I was using the wrong documentation for constructing dateFormat to parse times that come in predefined formats. maddy (below) provided a link to the correct documentation.

Here's what happened when I used the wrong format:

var idf = DateFormatter()
idf.locale = Locale(identifier: "en_US")
idf.dateStyle = .none
idf.dateFormat = "hh:MM:SSa"

// Of the variables defined here, the only one that doesn't cause an error 
// is the last one:
var sMidnight: String = "12:00:00AM"
var sEarly: String = "12:40:22AM"
var sMorning: String = "6:00:00AM"
var sNoon: String = "12:00:00PM"
var sAfternoon: String = "12:30:22PM"
var sEvening: String = "7:05:45PM"

// Put any of the variables besides sEvening here and you get a crash.
// "fatal error: unexpectedly found nil while unwrapping an Optional value"
var date: Date = idf.date(from: sEvening)!

print(idf.string(from: date)) // prints 07:05:45 PM

Solution

  • MM is for 2-digit month number. SS is for fractional seconds. Please review the documentation related to the format specifiers.

    You want:

    "h:mm:ssa"
    

    for your format.