Converting 24hrs to 12hrs in Swift

64 Views Asked by At

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

3

There are 3 best solutions below

0
xTwisteDx On

You don't need to convert that to a string. You can simply use the Date object you already have passed in. Your code is technically correct, but you've defined .dateFormat on your dateFormatter twice, which can cause some unexpected behavior, then you again format it. It could be doing that because of Locale information. Here's a proper way to handle it.

func getDate(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date12 = dateFormatter.string(from: date)
    print("12 hour formatted Date:", date12)
    return date12
}
2
vadian On

You convert a Date to String (with String Interpolation[!]) then to Date and finally again to String. This is a pretty pointless.

To use a string date format in DateFormatter you have to set the locale to a fixed value which is in 12-hour mode before specifying the format, the usual generic value is en_US_POSIX

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

But in iOS 15+, macOS 12+ there is a more convenient way to format dates

func formatDate(_ date: Date) -> String {
    date.formatted(.dateTime.hour().minute().locale(Locale(identifier: "en_US_POSIX")))
}
1
gnasher729 On

dateAsString is a textual representation intended for debugging. It displays the time and date in UTC which is likely not what you want. Don’t ever try to process it.

And converting that back to a Date is just pointless. When you want a date, use Date().