该库引入了一个与 Java 的 PeriodDuration 几乎等效的实现,原因是 Foundation 缺少对该标准的支持。
PeriodDuration 基于我之前开发的 一个库,但它超越了简单的序列化,引入了完全符合 ISO 8601 规范且支持 Codable 的专用类型。
可用类型:Period、Duration 和 PeriodDuration。
ISO 8601 将“Period”(周期)定义为年、月和日的组合。周期不包括小时、分钟或秒。
Period(years: 3, months: 1, days: 5) // = "P3Y1M5D"
ISO 8601 将“Duration”(持续时间)定义为小时、分钟或秒的组合。持续时间不包括年、月和日。
Duration(hours: 2, minutes: 5, seconds: 0) // = "PT2H5M0S"
PeriodDuration 是年、月、日、小时、分钟和秒的组合。作为一种类型,它内部包含一个 Period 和一个 Duration 实例来表示所有这些值。
PeriodDuration(years: 3, months: 1, days: 5, hours: 2, minutes: 5, seconds: 0) // = "P3Y1M5DT2H5M0S"
提供的所有三种类型都允许轻松转换为 Foundation 中内置的 DateComponents 类型。
let dateComponents: DateComponents = Period(years: 3, months: 1, days: 5).asDateComponents
这使得许多便利功能成为可能。具体来说:
Calendar.date(byAdding:to:wrappingComponents:) 将周期/持续时间添加到 Date 实例。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