Reputation: 388
I'm trying to get from 24 hrs like 5:00:00 to 5 am, but I'm having difficulty understanding how.
I have tried a few similar things, but eventually got to this:
let date: String = "5:00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
let theDate = dateFormatter.date(from: date)
dateFormatter.dateFormat = "HH:mm a"
myDateText.text = dateFormatter.string(from: theDate) // myDateText is a UILabel
I expected it to be 5 am but received an error that theDate is nil. I'm a newbie, so I would really appreciate any help.
Upvotes: 0
Views: 48
Reputation: 8680
HH is stand for 24 hours and hh is stand for 12 hours.
let date: String = "15:00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let theDate = dateFormatter.date(from: date)
dateFormatter.dateFormat = "hh:mm a"
print(dateFormatter.string(from: theDate!))
Output is 03:00 PM
Upvotes: 2