How to convert integer into time format with Swift?

Posted by Wei on July 10, 2017

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

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

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