Matt Kelly Matt Kelly - 4 years ago 954
Swift Question

Swift - Convert Milliseconds into Minutes, Seconds and Milliseconds

I am writing a racing app and want to convert a large number of milliseconds into minutes:seconds.milliseconds (for example,

1:32.361
). At the moment I just do it through maths (
minutes / 60000
), then get remainder and divide further, etc., but i find that it is off every now and then by 1 millisecond. I know this might not sound like a big deal, but I tried to find the average of
1:32.004
and
1:32.004
and it returned
1:32.003
, which means it gets put in incorrectly and the rest of the app can't deal with it.

Is there a way to use
NSDate
or
NSDateFormatter
or something like that to format the milliseconds into MM:ss.mmm?

I have looked at these sources but not found the answer:

How to convert milliseconds into minutes?

Convert seconds into minutes and seconds

Convert milliseconds to minutes

http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

Answer Source

You can create a NSTimeInterval extension to format your elapsed time as follow:

extension NSTimeInterval {
    var minuteSecondMS: String {
       return String(format:"%d:%02d.%03d", minute , second, millisecond  )
    }
    var minute: Int {
        return Int((self/60.0)%60)
    }
    var second: Int {
        return Int(self % 60)
    }
    var millisecond: Int {
        return Int(self*1000 % 1000 )
    }
}

extension Int {
    var msToSeconds: Double {
        return Double(self) / 1000
    }
}

let seconds = 131.531   // 131.531
let time = seconds.minuteSecondMS  //  "2:11.531"
let millisecond = seconds.millisecond    // 531

let ms = 1111
let sec = ms.msToSeconds.minuteSecondMS   // "0:01.111"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download