Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to parse date & time string with timezone abbreviation?

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?

like image 805
Mateusz Chechliński Avatar asked Dec 07 '25 20:12

Mateusz Chechliński


2 Answers

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.

like image 123
Mateusz Chechliński Avatar answered Dec 09 '25 16:12

Mateusz Chechliński


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))
like image 39
vadian Avatar answered Dec 09 '25 14:12

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!