I need convert this string 2020-03-18T00:00:00
in date like this 2020.03.18 00:00
When i try to convert like this my app just crash.
public extension String {
var dateValue: Date {
let formatter = DateFormatter()
formatter.timeZone = .none
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.date(from: self)!
}
}
Any ideas?
The issue is that this code is using a dateFormat
string of yyyy-MM-dd HH:mm
, but that’s not what the actual input string is. It is yyyy-MM-dd'T'HH:mm:ss
. Thus the conversion to the Date
object is failing, and the forced unwrapping will cause it to crash.
Instead, I would recommend one formatter to convert the ISO8601 format of 2020-03-18T00:00:00
into a Date
object. And if you then want a string in the format of 2020.03.18 00:00
, you would have a separate formatter for that.
In the absence of an explicit timezone in ISO8601 date strings, it’s assumed to be the local time zone. So do not specify the timeZone
property at all. (The only time you’d generally specify it is if it was Zulu/GMT/UTC, i.e. TimeZone(secondsFromGMT: 0)
.)
E.g.
let iso8601Formatter = DateFormatter()
iso8601Formatter.locale = Locale(identifier: "en_US_POSIX")
iso8601Formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy.MM.dd HH:mm"
func convert(input: String) -> String? {
guard let date = iso8601Formatter.date(from: input) else { return nil }
return formatter.string(from: date)
}
let result = convert(input: "2020-03-18T00:00:00") // "2020.03.18 00:00"
Note, instantiation of formatters (and changing of dateFormat
strings) is a notoriously computationally intensive process, which is why I made these formatters properties rather than local variables. Obviously name them whatever you want and put them wherever you want, but make sure you avoid repeatedly instantiating these formatters or changing of dateFormat
strings.