I'm trying to make a timestamp-app where you capture the times with one button.
When the button is pressed it prints out the current time 00:00:00
.
When the button is pressed the second time it prints out the current time again (i.e 00:00:15
).
I then want it to calculate the difference in time between the two timestamps (10 seconds).
I am new to objective-c and I have been sitting with this tiny problem for hours. Would be nice to have a pointer in the right direction.
I'm having problems with the timeIntervalSinceDate
. Here is the code:
- (IBAction)checkButton:(id)sender {
if (buttonPress) {
self.checkInStamp = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
checkInTime.text = [timeFormatter stringFromDate:checkInStamp];
buttonPress = false;
}
else {
self.checkOutStamp = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
checkOutTime.text = [timeFormatter stringFromDate:checkOutStamp];
NSTimeInterval timeDifference = [checkOutStamp timeIntervalSinceDate:checkInStamp];
totalDuration.text = @"%d", timeDifference; //<-This gives "Expression result unused on build"
}
}
Thank you for any help!
The difference between two NSDate
objects is obtained using the [NSDate timeIntervalSinceDate:]
method (reference) and is expressed as a NSTimeInterval
(a typedef
'd double
):
NSTimeInterval difference = [self.checkOutStamp timeIntervalSinceDate:self.checkInStamp];
NSLog(@"Difference is %f seconds", difference);