HelloWorld
HelloWorld

Reputation: 388

How to use Date Formatter to get from 00:00:00 (through 23:00:00) to 1 - 12 am/pm format?

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

Answers (1)

PinkeshGjr
PinkeshGjr

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

Related Questions