Formatting Duration in Swift

Mykhailo Moiseienko
4 min readMay 24, 2023

--

Formatting durations in Swift is crucial for presenting time-related information clearly and intuitively. Swift provides a handy tool called DateComponentsFormatter that simplifies the process of formatting time intervals into human-readable strings. In this article, we will explore the capabilities of DateComponentsFormatter and discover how it can help us format durations effortlessly in Swift.

To start, you need to create an instance of DateComponentsFormatter.

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute]
formatter.unitsStyle = .abbreviated

In the given code snippet, an instance of DateComponentsFormatter named formatter is created. Upon creation, the formatter is initialized with default settings, including the current locale. However, you have the flexibility to adjust these settings to meet your specific requirements.

To customize the formatter, you can modify its properties.

In this case, the allowedUnits property is set to an array containing the .day, .hour, and .minute units. By specifying the allowed units, you can control which components of the duration should be included in the formatted output. Larger or smaller units will be automatically omitted.

Additionally, the unitsStyle property is set to .abbreviated, which determines the style of the units used in the formatted output.

Later, we will consider other available styles in more detail, allowing you to explore further formatting options provided by DateComponentsFormatter and refine the presentation of time durations in Swift.

There are 3 ways how you can create a string representation of time quantity:

  • Use TimeInterval instance. Formatter will return a string based on the specified number of seconds.
let timeInterval: TimeInterval = 9_000

let formattedDuration = formatter.string(from: timeInterval)
print(formattedDuration) // Output: "2h 30m"
  • Use DateComponents instance. Formatter will return a string based on the specified date component information.
let dateComponents = DateComponents(hour: 2, minute: 30)

let formattedDuration = formatter.string(from: dateComponents)
print(formattedDuration) // Output: "2h 30m"
  • Use two instances of Date. Formatter will return a string based on the time difference between two dates.
let fromDate = Date()
let toDate = Date(timeIntervalSinceNow: 9_000)

let formattedDuration = formatter.string(from: fromDate, to: toDate)
print(formattedDuration) // Output: "2h 30m"

Units Style

There are 6 built-in units style that you can use:

1️⃣ Positional Units Style, e.g. “2:30”

formatter.unitsStyle = .positional

2️⃣ Abbreviated Units Style, e.g., “2h 30m”

formatter.unitsStyle = .abbreviated

3️⃣ Short Units Style, e.g., “2 hr, 30 min”

formatter.unitsStyle = .short

4️⃣ Full Units Style, e.g., “2 hours, 30 minutes”

formatter.unitsStyle = .full

5️⃣ Spell Out Units Style, e.g., “two hours, thirty minutes”

formatter.unitsStyle = .spellOut

6️⃣ Brief Units Style, e.g., “2hr 30min”

formatter.unitsStyle = .brief

Extras

In addition to basic duration formatting, the DateComponentsFormatter class in Swift offers some useful extras that enhance the presentation of time durations. These extras include the Approximation Phrase and Time Remaining Phrase features, which provide additional context and clarity to the formatted duration.

Approximation Phrase

When dealing with durations that are not precise or exact, it is beneficial to include an approximation phrase. The Approximation Phrase feature in DateComponentsFormatter adds words like “about”, “around” or “approximately” to indicate that the presented duration is an estimate rather than an exact value.

To enable the Approximation Phrase, simply set the includesApproximationPhrase property of DateComponentsFormatter to true.

formatter.includesApproximationPhrase = true

let timeInterval: TimeInterval = 9_000
let formattedDuration = formatter.string(from: timeInterval)
print(formattedDuration) // Output: "About 2hr 30min"

Time Remaining Phrase

When displaying countdowns, progress indicators, or time remaining until a specific event, it is valuable to include a Time Remaining Phrase. This phrase informs the user that the presented duration represents the time remaining until a particular event or deadline.

To incorporate the Time Remaining Phrase set the includesTimeRemainingPhrase property of DateComponentsFormatter to true. The formatter will then append appropriate phrases such as “remaining” or “left” to the formatted output, providing clear context about the duration.

formatter.includesTimeRemainingPhrase = true

let timeInterval: TimeInterval = 9_000
let formattedDuration = formatter.string(from: timeInterval)
print(formattedDuration) // Output: "2hr 30min remaining"

Conclusions

Throughout this article, we explored the fundamentals of using DateComponentsFormatter to format durations, including setting up a formatter instance, specifying allowed units, and selecting appropriate units styles. We also delved into advanced techniques such as using the Approximation Phrase and Time Remaining Phrase to provide additional context and clarity to the formatted durations.

Remember to consider the requirements and context of your application when selecting the appropriate formatting options, and feel free to experiment and iterate to find the most effective presentation for your specific use cases.

If you’re interested in learning how to format date intervals in the form <start> - <end> using DateComponentsFormatter — be sure to check out this article.

Thanks for reading!

--

--

Mykhailo Moiseienko

📱 Senior iOS Software Engineer. ✍️ Writing about iOS Development, Swift, and SwiftUI.