I made this extension of String to convert a string like "2018-10-04 23:12:42.640800" to another format. First I convert it to Date and then to String again.
extension String {
func convertDateFormater(to: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS+00:00"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = to
let completeDate = dt != nil ? dateFormatter.string(from: dt!):""
return completeDate
}
}
For example:
let myNewDate = "2018-10-04 23:12:42.640800".convertDateFormater(to: "dd MMM yyyy")
print(myNewDate) //04 oct. 2018
This work marvelous on my iPhone but on my iPad it just crashes. I don't understand why. That's why I made the completeDate
variable to stop the crash. But I need to change the format and it's not working.
Anybody know something about this?