How to parse an ISO-8601 duration in Objective C?

Zargony picture Zargony · Jul 18, 2009 · Viewed 7.8k times · Source

I'm looking for an easy way to parse a string that contains an ISO-8601 duration in Objective C. The result should be something usable like a NSTimeInterval.

An example of an ISO-8601 duration: P1DT13H24M17S, which means 1 day, 13 hours, 24 minutes and 17 seconds.

Answer

Igor Palaguta picture Igor Palaguta · Aug 5, 2016

Swift3,4,5 implementation: https://github.com/Igor-Palaguta/YoutubeEngine/blob/master/Source/YoutubeEngine/Parser/NSDateComponents%2BISO8601.swift

Example: let components = try DateComponents(ISO8601String: "P1Y2M3DT4H5M6S")

Tests: https://github.com/Igor-Palaguta/YoutubeEngine/blob/master/Tests/YoutubeEngineTests/ISO8601DurationTests.swift

Update: fixed for DougSwith case "P3W3DT20H31M21"