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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With