I cannot seem to figure out why only \"24:00\" returns nil instead of 12:00AM, whereas \"23:59\" returns correctly as 11:59PM.
let dateAsString = \"24:00\"
let d
You are using the wrong date format for the hour component. For values from 1-24 you have to use k
, if you have a leading zero you need to use kk
:
let dateAsString = "24:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "kk:mm"
if let date = dateFormatter.date(from: dateAsString) {
dateFormatter.dateFormat = "h:mm a"
let date2 = dateFormatter.string(from: date)
print(date2) // "12:00 AM\n"
}