Search code examples
swiftxcode6osx-yosemite

How do I get a tenth part of a second?


I try to make something in swift, and now I need to get a tenth part of a second from the system. I've checked the documentation and, from NSCalendar, I can take only nanoseconds.

func getTime()  {

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond , fromDate: dateNow)

    let x = CGFloat(components.nanosecond) * -1000000000
    println(x)

    let s = components.second
    cSeconds = s;

    let m  = components.minute     
    let h = components.hour     

     // code... 
} 

Have you you any idea how can I take this info from the system. O! I think it is ok if I get at least milliseconds, because I think it's much easier to work with it. Thanks.


Solution

  • One nanosecond is 10-9 seconds. Just divide the nanoseconds by 108 to get tenth of seconds, or by 106 to get milliseconds. Example:

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond , fromDate: dateNow)
    
    let t = components.nanosecond / 100000000
    let s = components.second
    let m  = components.minute
    let h = components.hour
    
    println(String(format:"%02ld:%02ld:%02ld.%01ld", h, m, s, t))
    // 14:27:12.3