IamMashed IamMashed - 6 months ago 24
Swift Question

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 is too many forms of solution and I could not find the one including the milliseconds. (the 789 milliseconds part)

Answer

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))
Comments