Contents

Duration.TimeFormatStyle

A format style that shows durations in a compact, localized format with separators.

Declaration

struct TimeFormatStyle

Overview

This style produces formatted strings that uses separators between components, like “2:03”

Create a TimeFormatStyle by providing a Duration.TimeFormatStyle.Pattern and an optional locale. The pattern specifies which units (hours, minutes, and seconds) to include in the formatted string, with optional configuration of the units. Then create a formatted string by calling formatted(_:) on a duration, passing the style, or format(_:) on the style, passing a duration. You can also use the style’s attributed property to create a style that produces AttributedString instances, which contains attributes that indicate the unit value of formatted runs of the string.

In situations that expect a Duration.TimeFormatStyle, such as formatted(_:), you can use the convenience function Swift/Duration/TimeFormatStyle/time(pattern:) to create a Duration.TimeFormatStyle, rather than using the full initializer.

If you want to reuse a style to format many durations, call format(_:) on the style, passing in a new duration each time.

The following example creates duration to represent 1 hour, 10 minutes, 32 seconds, and 400 milliseconds. It then creates a Duration.TimeFormatStyle to show hours, minutes, and seconds, padding the hours part to two digits and limiting the fractional seconds to two digits. When used with the formatted(_:) method, the resulting string is 01:10:32.40.

let duration = Duration.seconds(70 * 60 + 32) + Duration.milliseconds(400)
let format = duration.formatted(
    .time(pattern: .hourMinuteSecond(padHourToLength: 2,
                                     fractionalSecondsLength: 2)))
// format == "01:10:32.40"

Topics

Creating a time format style

Formatting a duration

Formatting a duration as an attributed string

Using a style pattern

Working with locales

Instance Properties

Instance Methods

See Also

Formatting a duration