Apple Swift:如何以 1/100 或 1/1000 获取当前秒数?
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
}
}
我想知道如何更改此代码,以便在 counterlabel.text 中显示 1/10 或 1/100 或 1/1000 秒。
就是想不通...谢谢!
纳秒有一个日历单位:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitNanosecond, fromDate: date)
let nanoSeconds = components.nanosecond
更新 Swift 3
let date = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.nanosecond], from: date)
let nanoSeconds = components.nanosecond
这给出秒的小数部分,单位为 10-9 秒。
对于毫秒,只需将此值除以 106:
let milliSeconds = nanoSeconds / 1_000_000
或者,如果您只想显示小数
秒,使用 NSDateFormatter
和 SSS
格式。示例:
let fmt = NSDateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
更新 Swift 3
let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
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 秒。 就是想不通...谢谢!
纳秒有一个日历单位:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitNanosecond, fromDate: date)
let nanoSeconds = components.nanosecond
更新 Swift 3
let date = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.nanosecond], from: date)
let nanoSeconds = components.nanosecond
这给出秒的小数部分,单位为 10-9 秒。 对于毫秒,只需将此值除以 106:
let milliSeconds = nanoSeconds / 1_000_000
或者,如果您只想显示小数
秒,使用 NSDateFormatter
和 SSS
格式。示例:
let fmt = NSDateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
更新 Swift 3
let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)