Swift 5 extension which converts ISO 8601 duration strings into a DateComponents
object.
PT12H = 12 hours
P3D = 3 days
P3DT12H = 3 days, 12 hours
P3Y6M4DT12H30M5S = 3 years, 6 months, 4 days, 12 hours, 30 minutes and 5 seconds
P10W = 70 days
For more information look here: https://en.wikipedia.org/wiki/ISO_8601#Durations
let durationString = "P3Y6M4DT12H30M5S"
let components = DateComponents.durationFrom8601String(durationString)
components?.year // 3
components?.month // 6
components?.day // 4
components?.hour // 12
components?.minute // 30
components?.second // 5
let durationStringInWeeks = "P8W"
let componentsForWeeks = DateComponents.durationFrom8601String(durationStringInWeeks)
componentsForWeeks?.day //56
You can use SPM. Add the following to your Package.swift
.
.package(url: "https://github.com/leonx98/Swift-ISO8601-DurationParser.git", .upToNextMajor(from: "1.0.0")),
If you like my open source libraries, you can sponsor it!
Swift/ISO8601-Duration Parser is available under the MIT license. See the LICENSE file for more info.
Objective-C version from @kevinrandrup