开发者

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

开发者 https://www.devze.com 2023-02-03 19:05 出处:网络
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 ev

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!


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
}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消