【问题标题】:Calculating elapsed time at different points of time from a fixed start time从固定开始时间计算不同时间点的经过时间
【发布时间】:2016-04-26 09:54:05
【问题描述】:

我在 Swift Playground 中执行了以下代码。我预计“第一秒”计数为 5,“第二秒”计数为 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)")

【问题讨论】:

    标签: swift nsdate nscalendar elapsedtime


    【解决方案1】:

    你有一个错字。

    let seconds1 = datecomponenets.second
    

    应该是

    let seconds1 = datecomponenets1.second
    

    然后它将按预期工作。

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2016-04-25
      • 2020-12-01
      • 1970-01-01
      相关资源
      最近更新 更多