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.
Available types: Period, Duration and PeriodDuration.
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"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 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"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).asDateComponentsThis allows for a number of handy things. Namely:
- Date manipulation: adding periods/durations to
Dateinstances viaCalendar.date(byAdding:to:wrappingComponents:). - Human-readable formatting via
DateComponentsFormatter.
MacBook Pro (14-inch, 2021)
Apple M1 Pro (10 cores, 8 performance and 2 efficiency)
32 GB Memory
$ swift run -c release Benchmarks
name time std iterations
------------------------------------------------------
parse PeriodDuration 1041.000 ns ± 26.34 % 1000000
print PeriodDuration 1291.000 ns ± 12.34 % 1000000
parse Period 1333.000 ns ± 13.65 % 1000000
print Period 666.000 ns ± 38.67 % 1000000
parse Duration 1041.000 ns ± 33.51 % 1000000
print Duration 666.000 ns ± 16.86 % 1000000