Question

There is an integer represents duration time in seconds, I want to convert it into 4:34:54 and 4 Hours 34 Minutes 54 seconds format. Is there any way to solve this problem?

Answer

The following code is based on Swift 3.

Format One

1
2
3
4
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
let formattedString = formatter.string(from: TimeInterval(interval))!

In this way, formattedString will be 7:30:05

Format Two

1
2
3
4
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!

In this way, formattedString will be 7 hours, 30 minutes, 5 seconds

Reference


This is the end of post