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 would like to know how I can change this code to get 1/10 or 1/100 or 1/1000 seconds to display in counterlabel.text. I just can't figure it out ... thanks!

+4
source share
1 answer

There is a calendar block 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 seconds in units of 10 -9 seconds. For milliseconds, simply divide this value by 10 6 :

let milliSeconds = nanoSeconds / 1_000_000

Alternatively, if you just want to display fractional seconds, use the NSDateFormatterand format SSS. 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)
+9
source

Source: https://habr.com/ru/post/1583961/


All Articles