Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion from NSTimeInterval to hour,minutes,seconds,milliseconds in swift

My code is here:

func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {      var ti = NSInteger(interval)     var ms = ti * 1000     var seconds = ti % 60     var minutes = (ti / 60) % 60     var hours = (ti / 3600)        return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms) } 

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

like image 835
Lydia Avatar asked Mar 05 '15 07:03

Lydia


People also ask

How do you convert milliseconds to seconds in IOS Swift?

To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds. To avoid having to do this every time, you can write an extension to do it.

What is NSTimeInterval?

A NSTimeInterval value is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. On its own, a time interval does not specify a unique point in time, or even a span between specific times.

How do you convert integers to seconds?

To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).


1 Answers

Swift supports remainder calculations on floating-point numbers, so we can use % 1.

var ms = Int((interval % 1) * 1000) 

as in:

func stringFromTimeInterval(interval: TimeInterval) -> NSString {    let ti = NSInteger(interval)    let ms = Int((interval % 1) * 1000)    let seconds = ti % 60   let minutes = (ti / 60) % 60   let hours = (ti / 3600)    return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms) } 

result:

stringFromTimeInterval(12345.67)                   "03:25:45.670" 

Swift 4:

extension TimeInterval{          func stringFromTimeInterval() -> String {              let time = NSInteger(self)              let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)             let seconds = time % 60             let minutes = (time / 60) % 60             let hours = (time / 3600)              return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)          }     } 

Use:

self.timeLabel.text = player.duration.stringFromTimeInterval() 
like image 165
Matthias Bauch Avatar answered Oct 19 '22 10:10

Matthias Bauch