Black Friday deal: 30% off our book "Integrating SwiftUI into UIKit apps"! Learn more ...Black Friday deal:30% off "Integrating SwiftUI into UIKit apps" >>
Quick Tip Icon
Quick Tip

Display high precision time with Duration and TimeFormatStyle

In iOS 16 and macOS 13 the Foundation framework has a new way of representing and formatting an elapsed time value with high precision in an integral form. We can use the new Duration type to represent the length of a video, time remaining to download a file, or a duration of a workout in our apps.

let timeRemaining: Duration = .seconds(6900)
Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover
Black Friday offer
Our book "Integrating SwiftUI into UIKit apps" is now 30% off!

Discover various ways to adopt SwiftUI in existing UIKit projects and take full advantage of the new iOS 16 frameworks and APIs such as Swift Charts.

The offer is active until the 1st of December.

To display this value to the users, we can format it with the new Duration.TimeFormatStyle. We can choose a pattern to apply, such as hourMinute, hourMinuteSecond, or minuteSecond, and even customize it further with a padding to the hour or minute field and a rounding rule for seconds or fractional seconds.

// 1:55
let hourMinute = timeRemaining.formatted(
    .time(pattern: .hourMinute)

// 01:55
let padHourToLength2 = timeRemaining.formatted(
    .time(pattern: .hourMinute(padHourToLength: 2))

// 1:55:00
let hourMinuteSecond = timeRemaining.formatted(
    .time(pattern: .hourMinuteSecond)

// 115:00
let minuteSecond = timeRemaining.formatted(
    .time(pattern: .minuteSecond)

To display such values in our SwiftUI applications we can interpolate the duration inside a Text view and format it in place.

Text("\(timeRemaining, format: .time(pattern: .hourMinuteSecond))")