Search code examples
iosswiftnsdateformatter

Get only time from Date


How to get only time from the date with am/pm. Below is my code what I have tried so far:

func changeFormat(str:String) -> String {
    let dateFormatter = DateFormatter()
    let newDateFormatter = DateFormatter()
    
    // step 1
    dateFormatter.dateFormat = "MM/dd/yyyy HH:mm aa" // input format
    newDateFormatter.dateFormat = "HH:mm aa" // output format
    
    let date = dateFormatter.date(from: str)!

    // step 2
    
    let string = newDateFormatter.string(from: date)
    
    
    return string
}

Usage:

let strTimeFromDate = changeFormat(str: self.response?.Data[indexPath.row].ADateTime ?? "")

input date:

06/22/2021 2:00 PM

output:

12:45 PM

Getting wrong time return after formatting. Please guide what's wrong with above code


Solution

  • "HH" is for 24h format and "aa" is for 12h format so you can't mix them, so you should use "hh:mm a" instead for both DateTimeFormatter's