我如何获得十分之一秒?

How do I get a tenth part of a second?

我尝试在swift中做点什么,现在我需要从系统中获取十分之一秒。我检查了文档,从 NSCalendar 开始,我只需要几纳秒。

func getTime()  {

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond , fromDate: dateNow)

    let x = CGFloat(components.nanosecond) * -1000000000
    println(x)

    let s = components.second
    cSeconds = s;

    let m  = components.minute     
    let h = components.hour     

     // code... 
} 

你知道我怎样才能从系统中获取这些信息吗?哦!我认为如果我得到至少毫秒就可以了,因为我认为使用它更容易。 谢谢

一纳秒是 10-9 秒。 只需将纳秒除以 108 即可得到十分之一秒, 或按 106 得到毫秒。 示例:

let dateNow = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond , fromDate: dateNow)

let t = components.nanosecond / 100000000
let s = components.second
let m  = components.minute
let h = components.hour

println(String(format:"%02ld:%02ld:%02ld.%01ld", h, m, s, t))
// 14:27:12.3

一秒有1,000,000,000纳秒,一秒有1,000毫秒。因此,您只需将纳秒除以 1,000,000 即可转换为毫秒,并将结果四舍五入为最接近的毫秒间隔。

let milliseconds = round(CGFloat(components.nanosecond) / 1000000)

你可以使用 NSDateFormatter 来获取毫秒数吗?

let dateNow = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd hh:mm:ss:SSS"
println(dateFormatter .stringFromDate(dateNow))

SSS 表示毫秒。