计算从固定开始时间开始的不同时间点的经过时间

时间:2016-04-26 09:54:05

标签: swift nsdate nscalendar elapsedtime

我在Swift Playground中执行了以下代码。我预计“First Seconds”计数为5,“Second Seconds”计数为10,因为两者的startDt与起点相同。但两者在输出中都是5。我在这里错过了什么吗?

let startDt = NSDate()
sleep(5)
let endDt = NSDate()
let calendar = NSCalendar.currentCalendar()
let datecomponenets = calendar.components([NSCalendarUnit.Second] , fromDate: startDt, toDate: endDt, options: [] )
let seconds = datecomponenets.second
print("First Seconds: \(seconds)")

sleep(5)
let endDt1 = NSDate()
let calendar1 = NSCalendar.currentCalendar()
let datecomponenets1 = calendar.components([NSCalendarUnit.Second] , fromDate: startDt, toDate: endDt1, options: [] )
let seconds1 = datecomponenets.second
print("Second Seconds: \(seconds1)")

1 个答案:

答案 0 :(得分:1)

你有一个错字。

let seconds1 = datecomponenets.second

应该是

let seconds1 = datecomponenets1.second

然后它将按预期工作。