Unable to convert date string "2017-01-01 13:40:15.314" to "dd MMMM yyy hh:mm a" format

446 Views Asked by At

unable to convert string to date format with AM/PM

my sample code:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat =  "yyyy-MM-dd HH:mm:ss.SSS"

if let todaysDate:Date = dateFormatter.date(from: dateString) {

    let newdateFormatter:DateFormatter = DateFormatter()
    newdateFormatter.dateFormat = "dd MMMM yyy hh:mm a"
    newdateFormatter.amSymbol = "AM"
    newdateFormatter.pmSymbol = "PM"

    return newdateFormatter.string(from: todaysDate)
}

input is: "2017-01-01 13:40:15.314"

output is: 01 January 2017 19:57

expected out put is: 01 January 2017 7:57 PM

1

There are 1 best solutions below

2
On BEST ANSWER

Set the locale of the date formatter to en_US_POSIX, as a side-effect it sets the AM/PM symbols to uppercase, too.

let newdateFormatter = DateFormatter() // Do not annotate types the compiler can infer
newdateFormatter.locale = Locale(identifier: "en_US_POSIX")
newdateFormatter.dateFormat = "dd MMMM yyyy h:mm a"
newdateFormatter.string(from: todaysDate)