BeachRunnerFred
BeachRunnerFred

Reputation: 18578

iOS Development: What's a simple way to calculate the number of seconds that have passed between two events?

I need to calculate the number of seconds that have passed between two events on the iPhone. To do so, I need to store the time that the first event occurred and check it against the time the second event occurred to see if more than 30 seconds has passed.

I'm about to begin trying to accomplish this using the NSDate class, but I was wondering if there's a simpler way to do this without using objects, as I would prefer to store simple, intrinsic values instead of objects.

Thanks for your wisdom!

Upvotes: 5

Views: 1594

Answers (3)

justin
justin

Reputation: 104698

have you seen UIEvent's timestamp?

example:

double event1Timestamp, event2Timestamp; ///< ivars in your class?

{ // some function/method body
  event1Timestamp = event1.timestamp;
}

{ // some other function/method body
  /*** later that day ***/
  event2Timestamp = event2.timestamp;
  if (30 <= (event2Timestamp-event1Timestamp)) {
    printf("ok, it's been 30 seconds");
  }
}

where event1 and event2 are naturally the incoming events

Upvotes: 0

Sam Dufel
Sam Dufel

Reputation: 17598

If you really want to avoid storing objects, you can do something like:

double startTime = [[NSDate date] timeIntervalSince1970];

//Run your other code

double endTime = [[NSDate date] timeIntervalSince1970];

if (endTime - startTime > 30) {
  //30 seconds have passed
}

Upvotes: 7

Robin
Robin

Reputation: 10011

You can use [NSDate dateWithTimeIntervalSinceReferenceDate:anotherDate]; or use the initWithTimeIntervalSinceReferenceDate: method

Upvotes: 0

Related Questions