Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apple Swift: how to get current seconds in 1/100 or 1/1000?

func updateTime() {
    var date = NSDate()
    var calendar = NSCalendar.currentCalendar()
    var components = calendar.components(.CalendarUnitSecond, fromDate: date)
    var hour = components.hour
    var minutes = components.minute
    var seconds = components.second
    counterLabel.text = "\(seconds)"

    var myIndicator = counterLabel.text?.toInt()

    if myIndicator! % 2 == 0 {
        // do this
    } else {
       // do that
    }
}

I'd like to know how I can change this code so I get 1/10 or 1/100 or 1/1000 of a second to display in counterlabel.text. Just can't figure it out... thanks!

like image 255
stnbrk Avatar asked Apr 22 '15 08:04

stnbrk


1 Answers

There is a calendar unit for nanoseconds:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitNanosecond, fromDate: date)
let nanoSeconds = components.nanosecond

Update for Swift 3

let date = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.nanosecond], from: date)
let nanoSeconds = components.nanosecond

This gives the fractional part of the seconds in units of 10-9 seconds. For milliseconds, just divide this value by 106:

let milliSeconds = nanoSeconds / 1_000_000

Alternatively, if you just want to display the fractional seconds, use a NSDateFormatter and the SSS format. Example:

let fmt = NSDateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)

Update for Swift 3

let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
like image 90
Martin R Avatar answered Sep 28 '22 05:09

Martin R