PeriodDuration

CI

该库引入了一个与 Java 的 PeriodDuration 几乎等效的实现,原因是 Foundation 缺少对该标准的支持。

PeriodDuration 基于我之前开发的 一个库,但它超越了简单的序列化,引入了完全符合 ISO 8601 规范且支持 Codable 的专用类型。

用法

可用类型:PeriodDurationPeriodDuration

Period(周期)

ISO 8601 将“Period”(周期)定义为的组合。周期包括小时分钟

Period(years: 3, months: 1, days: 5) // = "P3Y1M5D"

Duration(持续时间)

ISO 8601 将“Duration”(持续时间)定义为小时分钟的组合。持续时间包括

Duration(hours: 2, minutes: 5, seconds: 0) // = "PT2H5M0S"

PeriodDuration

PeriodDuration小时分钟的组合。作为一种类型,它内部包含一个 Period 和一个 Duration 实例来表示所有这些值。

PeriodDuration(years: 3, months: 1, days: 5, hours: 2, minutes: 5, seconds: 0) // = "P3Y1M5DT2H5M0S"

转换为 DateComponents

提供的所有三种类型都允许轻松转换为 Foundation 中内置的 DateComponents 类型。

let dateComponents: DateComponents = Period(years: 3, months: 1, days: 5).asDateComponents

这使得许多便利功能成为可能。具体来说:

基准测试

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