Apple Swift:如何以 1/100 或 1/1000 获得当前秒数? [英] Apple Swift: how to get current seconds in 1/100 or 1/1000?
本文介绍了Apple Swift:如何以 1/100 或 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
}
}
我想知道如何更改此代码,以便在 counterlabel.text 中显示 1/10 或 1/100 或 1/1000 秒.就是想不通……谢谢!
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!
推荐答案
有一个以纳秒为单位的日历单位:
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
Swift 3 的更新
Update for Swift 3
let date = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.nanosecond], from: date)
let nanoSeconds = components.nanosecond
这给出了以 10-9 秒为单位的秒的小数部分.对于毫秒,只需将此值除以 106:
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
或者,如果您只想显示小数秒,使用 NSDateFormatter
和 SSS
格式.示例:
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)
Swift 3 的更新
Update for Swift 3
let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
这篇关于Apple Swift:如何以 1/100 或 1/1000 获得当前秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文