PeriodDuration
This library introduces a close equivalent to Java's PeriodDuration, motivated by the lack of support for this standard in Foundation.
PeriodDuration
is based off of a previous library I worked on, however it goes beyond simple serialization by introducing dedicated types with full ISO 8601 compliant Codable
support.
Usage
Available types: Period
, Duration
and PeriodDuration
.
Period
ISO 8601 defines a "Period" as a combination of years, months, and days elapsed. Periods do not include hours, minutes or seconds.
Period(years: 3, months: 1, days: 5) // = "P3Y1M5D"
Duration
ISO 8601 defines a "Duration" as a combination of hours, minutes or seconds elapsed. Durations do not include years, months, and days.
Duration(hours: 2, minutes: 5, seconds: 0) // = "PT2H5M0S"
PeriodDuration
PeriodDuration
is a combinations of years, months, days, hours, minutes and seconds elapsed. As a type, it holds both a Period
and a Duration
instance within it to represent all of these values.
PeriodDuration(years: 3, months: 1, days: 5, hours: 2, minutes: 5, seconds: 0) // = "P3Y1M5DT2H5M0S"
Conversion to DateComponents
All three types provided allow for easy conversion into the built-in DateComponents
type in Foundation.
let dateComponents: DateComponents = Period(years: 3, months: 1, days: 5).asDateComponents
This allows for a number of handy things. Namely:
- Date manipulation: adding periods/durations to
Date
instances viaCalendar.date(byAdding:to:wrappingComponents:)
. - Human-readable formatting via
DateComponentsFormatter
.