tags:

views:

24

answers:

3

I'm trying to use timeIntervalSinceReferenceDate and I'm not quite sure if I understand it correctly. I basically have a button to calculate the difference in time between when the start and stop button is pressed.

- (IBAction)startButtonPressed {
    startButtonFlag = !startButtonFlag; // first time through, startButtonFlag turns on
    if (startButtonFlag) { // timer starts
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
        startTime = [NSDate timeIntervalSinceReferenceDate];
        NSLog(@"start time: %d", startTime);
    }
    else { // timer stops
        [startButton setTitle:@"Start" forState:UIControlStateNormal]; 
        stopTime = [NSDate timeIntervalSinceReferenceDate];
        NSLog(@"stop time: %d", stopTime);      
        elapsedTime = stopTime - startTime;
        NSLog(@"elapsed time: %d", elapsedTime);
    }

}

I don't quite understand the output. My sample output is: start time: 558828278 stop time: 581239552 elapsed time: -1610612736

I pressed the stop button shortly after (5 seconds or so) after I pressed start. I was expecting that the stop time would be more like 558828283 so when I subtracted the two times, to see how much time has elapsed, I would get 5 seconds. Am I misunderstanding how the class method works? Thanks.

+1  A: 

you could try something like this instead:

NSDate* start = [NSDate date];
...

NSDate* stop = [NSDate date];
NSLog(@"took %lf seconds", [stop timeIntervalSinceDate:start]);
Anders K.
+1  A: 

Are startTime, stopTime, and elapsedTime declared as type NSTimeInterval or double?

In that case, you should use %f instead of %d (which is for ints).

aBitObvious
Thanks. For some reason I thought %d was for decimal.
Crystal
See [String Format Specifiers](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Strings/Articles/formatSpecifiers.html%23//apple_ref/doc/uid/TP40004265).
aBitObvious
A: 

Your using the wrong function:

[NSDate timeIntervalSinceReferenceDate];

Creates and returns an NSDate object set to a given number of seconds from the first instant of 1 January 2001, GMT.

You should be using something like

dateWithTimeIntervalSinceNow

Creates and returns an NSDate object set to a given number of seconds from the current date and time.

Rushil