Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a ISO8601 String to Date in Swift

Tags:

swift

I am getting the next string from an API which claims

All date formats are ISO8601.

I am trying with the next code:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let updatedAtStr = "2016-06-05T16:56:57.019+01:00"
let updatedAt = dateFormatter.date(from: updatedAtStr)

Unfortunately resulting updatedAt is nil

like image 358
Sergio del Amo Avatar asked Sep 11 '16 07:09

Sergio del Amo


People also ask

How to parse an ISO 8601 date from a string?

When parsing a date from a string, you might think of DateFormatter. You have to manually set dateFormat and locale to DateFormatter instance. You probably need this formatter every time you need to talk with API. Luckily, since iOS 10, Apple introduced a dedicated formatter for handling ISO 8601 date parsing, ISO8601DateFormatter.

How to convert a string to a date in Swift?

The class we use to convert a string to a date in Swift is DateFormatter (or NSDateFormatter if you are using Objective-C). I encourage you to follow along with me. Fire up Xcode and create a playground. As I mentioned in the introduction, the DateFormatter class is defined in the Foundation framework.

What is iso8601dateformatter in iOS 10?

Luckily, since iOS 10, Apple introduced a dedicated formatter for handling ISO 8601 date parsing, ISO8601DateFormatter. ISO8601DateFormatter is simpler than DateFormatter. We don't have to set locale of dateFormat. Less code means less chance we can do wrong with this new formatter.

What is the date format of the string passed to dateformat?

The date format of the string that is passed to date (from:) method is MM/dd/yy while the dateFormat property has a value of dd/MM/yy. In the eyes of the date formatter, the string that is passed to the date (from:) method is invalid.


1 Answers

Your date format is incorrect, you need to take into account the milliseconds.

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"

let updatedAtStr = "2016-06-05T16:56:57.019+01:00"
let updatedAt = dateFormatter.date(from: updatedAtStr) // "Jun 5, 2016, 4:56 PM"

Just to clarify, the addition of .SSS in the date format is what fixes the problem.

like image 129
Callam Avatar answered Sep 17 '22 11:09

Callam