I'm getting a response from api that is date string, it's format changes sometimes so I need to format it dynamically,
Here's my code
import Foundation
func format(from: String?, fromFormat: String, to: String) -> String {
if from == nil { return "" }
let inputDateFormatter = DateFormatter()
inputDateFormatter.dateFormat = fromFormat
let date = inputDateFormatter.date(from: from ?? "")
let outputDateFormatter = DateFormatter()
outputDateFormatter.dateFormat = to
if let date = date {
return outputDateFormatter.string(from: date)
}
return "not formatted"
}
let strFromApi = "2020-12-22"
print(format(from: strFromApi, fromFormat: "yyyy-MM-dd", to: "d MMM yyyy"))
As you can see, I have a code there that can format successfully, the problem here is that strFromApi
variable was came from api, and is changing between 2020-12-22
and 2020-12-22 00:00:00
, when it changes to 2020-12-22 00:00:00
, my current code can't format it anymore.
Question: How can I format it even the given format from the server has time?