Swift
Integer Conversion
Time Conversion
Programming
iOS Development

Swift - Integer conversion to Hours/Minutes/Seconds

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Converting a number of seconds into hours, minutes, and seconds is a common formatting task in Swift. The logic is simple integer arithmetic, but a good implementation also handles zero padding, negative values, and the distinction between raw components and display strings.

Break Seconds Into Components

The standard approach uses division and remainder operations.

swift
1import Foundation
2
3func hms(from totalSeconds: Int) -> (hours: Int, minutes: Int, seconds: Int) {
4    let hours = totalSeconds / 3600
5    let minutes = (totalSeconds % 3600) / 60
6    let seconds = totalSeconds % 60
7    return (hours, minutes, seconds)
8}
9
10let value = hms(from: 3671)
11print(value.hours, value.minutes, value.seconds)

For 3671, the result is 1 hour, 1 minute, and 11 seconds.

Format the Result for Display

Returning the numeric components is useful for calculations, but UI code usually needs a string.

swift
1import Foundation
2
3func formatHMS(_ totalSeconds: Int) -> String {
4    let hours = totalSeconds / 3600
5    let minutes = (totalSeconds % 3600) / 60
6    let seconds = totalSeconds % 60
7    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
8}
9
10print(formatHMS(3671))

That prints 01:01:11, which is often the most readable representation for timers and media durations.

Handle Durations Under One Hour

Sometimes you want mm:ss when the duration is shorter than an hour.

swift
1import Foundation
2
3func formatDuration(_ totalSeconds: Int) -> String {
4    let hours = totalSeconds / 3600
5    let minutes = (totalSeconds % 3600) / 60
6    let seconds = totalSeconds % 60
7
8    if hours > 0 {
9        return String(format: "%d:%02d:%02d", hours, minutes, seconds)
10    }
11    return String(format: "%02d:%02d", minutes, seconds)
12}
13
14print(formatDuration(59))
15print(formatDuration(3671))

That gives a shorter format for small values while still expanding naturally for longer ones.

Watch Out for Negative Values

If your app works with countdowns or offsets, negative input needs deliberate handling. Swift’s remainder behavior is mathematically valid, but it may not match a user-friendly display format.

swift
1import Foundation
2
3func safeFormatHMS(_ totalSeconds: Int) -> String {
4    let sign = totalSeconds < 0 ? "-" : ""
5    let absolute = abs(totalSeconds)
6    let hours = absolute / 3600
7    let minutes = (absolute % 3600) / 60
8    let seconds = absolute % 60
9
10    return sign + String(format: "%02d:%02d:%02d", hours, minutes, seconds)
11}
12
13print(safeFormatHMS(-75))

That produces -00:01:15, which is usually clearer than letting negative remainders appear in each component.

Use DateComponentsFormatter When You Need Locale-Aware Output

If you want a higher-level formatter, Foundation can format durations for you.

swift
1import Foundation
2
3let formatter = DateComponentsFormatter()
4formatter.allowedUnits = [.hour, .minute, .second]
5formatter.unitsStyle = .positional
6formatter.zeroFormattingBehavior = [.pad]
7
8print(formatter.string(from: 3671) ?? "")

This is useful when you want consistent system formatting without manually building every string. For straightforward timer displays, manual arithmetic is still easy to read and test.

Keep Calculation Logic Separate from Presentation

A good pattern is to return components from one function and format them in another. That keeps business logic reusable.

swift
1struct DurationParts {
2    let hours: Int
3    let minutes: Int
4    let seconds: Int
5}
6
7func splitDuration(_ totalSeconds: Int) -> DurationParts {
8    let absolute = abs(totalSeconds)
9    return DurationParts(
10        hours: absolute / 3600,
11        minutes: (absolute % 3600) / 60,
12        seconds: absolute % 60
13    )
14}

This is easier to test than a single function that mixes arithmetic, sign handling, and UI formatting.

Common Pitfalls

A common mistake is computing minutes with totalSeconds / 60, which ignores the hours already removed and produces values larger than 59. Another is forgetting zero padding, which makes timer strings jump in width as values change. Developers also sometimes format negative durations without taking the absolute value first, leading to awkward component output. Finally, if you only need a display string, avoid overcomplicating the problem with full date APIs.

Summary

  • Convert seconds with integer division and remainder.
  • Use String(format:) for fixed-width timer output.
  • Handle negative values explicitly if countdown-style display matters.
  • Consider DateComponentsFormatter for higher-level formatting.
  • Separate numeric conversion from presentation when the code will be reused.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.