ios – DateFormatter not working Swift with Hour and minute second


There are a lot of points on this code

  1. "" … "" is invalid syntax.
  2. There is no such thing as a parameter kind outlined.
  3. Nothing – and even the incorrect kind – is returned.
  4. Z is a format specifier, it should not be wrapped in single quotes.

Other than that have a look at your date string. A colon between seconds and milliseconds could be very unusual but it surely works with this code

func convertDateFormater(dateStr: String) -> Date? {
   let inputFormatter = DateFormatter()
   inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSSZ"
   return dateStr)

convertDateFormater(dateStr: "2022-10-22T22:22:16:2216Z")

However you can not convert each strings (colon and interval separator) with the identical date format.

To take action you want a second parameter

func convertDateFormater(dateStr: String, hasColonMillisecondSeparator: Bool = false) -> Date? {
    let inputFormatter = DateFormatter()
    inputFormatter.dateFormat = hasColonMillisecondSeparator ? "yyyy-MM-dd'T'HH:mm:ss:SSSZ" : "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    return dateStr)

convertDateFormater(dateStr: "2022-10-23T00:00:00.000Z")
convertDateFormater(dateStr: "2022-10-22T22:22:16:2216Z", hasColonMillisecondSeparator: true)


Leave a Reply