NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
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))")
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

100+ tips to take your Swift code to the next level

Swift Gems

100+ tips to take your Swift code to the next level

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift