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)
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
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))")