If you break down what you are trying to do, there are actually 2 steps that require two different date formatters.
- Convert an input date string (e.g. "2021-05-23T06:35:47.409Z") to a
Date
- Convert the
Date
to an output string in a different format.
Try this code instead:
var str = "2021-05-23T06:35:47.409Z"
//Set up a DateFormatter for input dates in "Internet" date format"
var inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
//Set up an output date formatter (in the local time zone)
var outputFormatter = DateFormatter()
outputFormatter.dateFormat = "MMM d yyyy, h:mm:ss a"
if let formattedtoDate = inputFormatter.date(from: str) {
let formattedtoString = outputFormatter.string(from: formattedtoDate)
print("'\(str)' = '\(formattedtoString)'")
} else {
print("Can't convert the string \(str) to a Date")
}
Edit:
(As Leo Dabus pointed out in a comment, you usually should not use a fixed dateFormat
string in a DateFormatter that generates user-visible date strings. Better to use date and time styles and let the DateFormattter pick a specific format appropriate to the user's locale and language.)