Format durations like a stopwatch or a sentence
Duration formats as 1:02:05 or as 1 hour, 2 minutes, in the guest's language, with no manual division into hours and minutes.
iOS 16+macOS 13+ Swift 5.9
Turning seconds into hours and minutes by hand means integer division, zero padding and pluralisation, and the result is English only. Swift’s Duration type has two format styles: a clock-like pattern and a spelled-out list of units.
import SwiftUI
struct WorkoutSummary: View {
let elapsed = Duration.seconds(3_725)
let lap = Duration.seconds(65.4)
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(elapsed, format: .time(pattern: .hourMinuteSecond))
.font(.largeTitle.monospacedDigit())
Text(elapsed, format: .units(allowed: [.hours, .minutes], width: .wide))
Text(elapsed, format: .units(allowed: [.hours, .minutes, .seconds], width: .narrow))
Text(lap, format: .time(pattern: .minuteSecond(padMinuteToLength: 2, fractionalSecondsLength: 1)))
}
}
}
#Preview {
WorkoutSummary()
}Converting from a TimeInterval is one call: Duration.seconds(interval).
How it works
.time(pattern:)gives clock-style output..hourMinuteSecond,.hourMinuteand.minuteSecondchoose the fields; the parameters control padding and fractions of a second..units(allowed:width:)spells the duration out..widegives words,.abbreviatedgives “1 hr, 2 min” and.narrowgives “1h 2m”.- The units style is localised, plurals included: in German the same duration reads “1 Stunde und 2 Minuten”.
Gotchas
- The largest allowed unit absorbs everything above it: with only
.minuteSecond, 3,725 seconds shows as 62:05. - Values are rounded to the smallest allowed unit, so drop seconds when you only show hours and minutes, rather than showing a misleading 0.
Durationmeasures elapsed time. For “how long until a date”, use relative date formatting instead.