Time.abs
func Time.abs(d: Time.Duration): Time.DurationTime.abs returns d with its sign made positive, or d itself when it is zero.
Details
Time.abskeeps the fields as given and drops only the sign:-PT90MgivesPT90M, notPT1H30M.- It panics when a field is the most negative
int, whose positive counterpart does not fit.
Basic examples
Time.abs(Time.duration(hours: -2)) // PT2H
Time.abs(2h) // PT2H
Time.abs(0s) // PT0SScope
Every field loses its sign, the calendar fields included:
Time.abs(Time.duration(years: -1, months: -2, days: -3)) // P1Y2M3D
Time.abs(Time.duration(milliseconds: -1500)) // PT1.5SCall it with a dot on a duration, such as one that Time.until returns:
let open = Time.plainTime(9, 0, 0)
let close = Time.plainTime(17, 30, 0)
Time.until(close, open) // -PT8H30M
Time.until(close, open).abs() // PT8H30MPass Time.abs as a function value:
[Time.duration(hours: -1), 30m].map(Time.abs) // [PT1H, PT30M]Applications
Check that two clocks agree within five minutes, whichever one is ahead:
func inSync(a: Time.Instant, b: Time.Instant): bool {
let drift = Time.until(a, b).abs()
Time.compareDuration(drift, 5m) <= 0
}
let server = Time.parseInstant("2026-10-22T14:03:05Z").unwrap()
let client = Time.parseInstant("2026-10-22T14:00:00Z").unwrap()
inSync(server, client) // true
inSync(client, server) // trueThe length of a gap between two times of day, in hours, in either order:
func gapHours(a: Time.PlainTime, b: Time.PlainTime): float64 {
Time.until(a, b).abs().total(Time.Hour{})
}
gapHours(Time.plainTime(9, 0, 0), Time.plainTime(10, 30, 0)) // 1.5
gapHours(Time.plainTime(10, 30, 0), Time.plainTime(9, 0, 0)) // 1.5Properties and relations
The result is never negative, ignores the sign of its argument, and leaves a nonnegative duration as it is:
let ds = [Time.duration(hours: -3), 0s, Time.duration(days: 2, minutes: 5)]
for d in ds {
assert(d.abs().sign() >= 0)
assert(d.negate().abs() == d.abs())
assert(d.abs() == (if d.sign() < 0 { d.negate() } else { d }))
}Possible issues
Time.abs does not balance, so == with a balanced duration is false. Compare lengths with Time.compareDuration:
let d = Time.abs(Time.duration(minutes: -90))
d == 1h30m // false
Time.compareDuration(d, 1h30m) == 0 // trueA field of the most negative int has no positive counterpart:
Time.abs(Time.duration(nanoseconds: Math.minInt))
// panic: Time.abs: the negated duration has a field that does not fit an intMath.abs takes numbers only, not durations:
let d = Time.negate(1h)
let e = Math.abs(d) // error: T would be Time.Duration, which is not a member of its bound NumberSee also
Time.negate, Time.sign, Time.compareDuration, Time.until, Math.abs, Time.Duration
