3

I receive a date & time string from a server with an information about a timezone formatted in an unusual way:

2017-05-05T12:24:16.286462Z[UTC]

I would like to use DateFormatter to parse it, but I cannot figure out what date format should I use.

I tried parsing it with "yyyy-MM-dd'T'HH:mm:ss.SSSZ'['R']'" or something quite similar but with no luck.

Here is my code:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en-US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ'['R']'"
let date = dateFormatter.date(from: date)

What is the right date format for this string?

2 Answers2

2

OK guys, I figured it out.

The right format is

"yyyy-MM-dd'T'HH:mm:ss.SSS'Z['zzz']'"

zzz is for a timezone abbreviation, while Z[ and ] are treated as a plain text.

1

An alternative approach with ISO8601DateFormatter. The [UTC] portion is stripped with Regular Expression

let dateString = "2017-05-05T12:24:16.286462Z[UTC]"

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: dateString.replacingOccurrences(of: "\\[^\\[+\\]", with: "", options: .regularExpression))
vadian
  • 274,689
  • 30
  • 353
  • 361