'convert milliseconds Integer into time formatted String

It might be an easy question but I am confused and need your help. I need to convert this:

let S: Int = 45296789

into this: "12 34 56 789"

that is to say S is the integer representing milliseconds. What I need is to format it into "hh mm ss iii"

One of the solution could be the following:

var a = S/1000/60/60
var b = S/1000/60%60
var c = S/1000 % 60
var d = S % 1000

String(format:"%02i %02i %02i %03i", a, b, c, d)

But what I need is a method using NSDateFormatter() or NSTimeFormatter() if it is possible.

I looked into stackoverflow but there are too many forms of solution and I could not find the one including the milliseconds. (the 789 milliseconds part)



Solution 1:[1]

Try this:

let s = 45296789

let date = NSDate(timeIntervalSince1970: Double(s) / 1000)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.dateFormat = "HH mm ss SSS"

print(formatter.stringFromDate(date))

Solution 2:[2]

swfit 5

    let milliseconds = 35347634

    let date = Date(timeIntervalSince1970: milliseconds / 1_000)

    let formatter = DateFormatter()
    formatter.timeZone = TimeZone(identifier: "UTC")
    formatter.dateFormat = "HH:mm:ss"

    print(formatter.string(from: date))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ali Hamad