toast toast - 20 days ago 5
Objective-C Question

Adding elapsed TimeInterval to Date()

I'm trying to add the elapsed time to a Date() object (its for the resume button of a timed operation).

Below is the resume portion of the code responsible for calculating the altered

startDate
. I'm expecting it to add the
elapsed
TimeInterval
to
startDate
.

This is the code:

print(startDate)
let elapsed = resumeTime - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)


This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.

Output:

2016-11-17 08:24:15 +0000
110.831687986851
2016-11-17 08:26:06 +0000


The second printed date should be more like:

2016-11-17 08:24:18 +0000


The definition for
addTimeInterval
is:


Add a TimeInterval to this Date.


Isn't this exactly what I want? Am I interpreting this incorrectly?

Note,
resumeTime
is defined when the pause button is tapped. It is set like this:

resumeTime = Date.timeIntervalSinceReferenceDate


Thanks.

Answer

This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.

Although, your elapsed time is 2 min.

Make sure that you start elapsed in the right place, also make sure that this line generates the desired timestamp:

resumeTime = Date.timeIntervalSinceReferenceDate

Here is example of code very similar to yours, addTimeInterval does work well.

let resume = Date().timeIntervalSinceReferenceDate + 2

print(startDate)
let elapsed = resume - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)

Output

2016-11-17 08:53:34 +0000
2.00815904140472
2016-11-17 08:53:36 +0000