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

青春壹個敷衍的年華 提交于 2019-12-10 15:34:59

问题


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!


回答1:


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)


来源:https://stackoverflow.com/questions/29791643/apple-swift-how-to-get-current-seconds-in-1-100-or-1-1000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!