ISO 8601 duration implementation for Swift using Codable.
This micro-framework should help with handling duration written using the ISO 8601 standard. It allows parsing a string like "P3Y6M4DT12H30M5S" to TimeInterval. More about ISO 8601 standard you can read in wiki https://en.wikipedia.org/wiki/ISO_8601#Durations
Usage is very simple, you can use Duration(string: String)
:
import ISO8601Duration
let duration = Duration(string: "P3Y6M4DT12H30M5S")
print(duration.timeInterval) //110615405.0
Or you can decode from JSON like this:
{
"duration": "P3Y6M4DT12H30M5S"
}
then you can create your own structure:
import ISO8601Duration
struct Box: Codable {
let duration: Duration
}
add load data in a typical way:
let data = Data(bytes: "{\"duration\":\"P3Y6M4DT12H30M5S\"}".utf8) //load you data
let decoder = JSONDecoder()
let box = try decoder.decode(Box.self, from: data)
print(box.duration.timeInterval) //110615405.0
Use the CocoaPods.
Add to your Podfile
pod 'ISO8601Duration'
and then call
pod install
and import
import ISO8601Duration