0

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

Bista
  • 7,869
  • 3
  • 27
  • 55

1 Answers1

1

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)
vadian
  • 274,689
  • 30
  • 353
  • 361