I'm trying to convert 24 hours to 12 hours and when I run the code it does not convert to 12 hours. I'm not sure what I'm doing wrong. Here's my code.
func getDate(date: Date) -> String {
let dateAsString = "\(date)" //2023-07-17 15:12:00 +0000
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
let date1 = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date1!)
print("12 hour formatted Date:",Date12)
return Date12
}
Here's what is rendered.
12 hour formatted Date: 08:18
2023-07-17 15:13:00 +0000
You don't need to convert that to a string. You can simply use the
Dateobject you already have passed in. Your code is technically correct, but you've defined.dateFormaton yourdateFormattertwice, which can cause some unexpected behavior, then you again format it. It could be doing that because ofLocaleinformation. Here's a proper way to handle it.