Search code examples
swiftnsdatenscalendarelapsedtime

Calculating elapsed time at different points of time from a fixed start time


I executed the below code in Swift Playground. I expected the "First Seconds" count to be 5 and the "Second Seconds" count to be 10, as both have the same startDt as the starting point. But both turned out to be 5 in the output. Am I missing something here?

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)")

Solution

  • You have a typo.

    let seconds1 = datecomponenets.second
    

    Should be

    let seconds1 = datecomponenets1.second
    

    Then it will work as expected.