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)

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))")
Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with iOS 16 features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit