0

I want to store the amount of time that has passed within NSDate. So when a button is trigger i want a timer to start counting, i guess in seconds, and then store how much time has passed till the user has hit the next button within NSDate so I can subtract this value from another NSDate to get the difference with a NSTimeInterval.

NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:(slider.value * 60)];

        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:[date timeIntervalSinceNow] target:self selector:@selector(nextFunction) userInfo:nil repeats:NO];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
4GetFullOf
  • 1,738
  • 4
  • 22
  • 47

1 Answers1

3

NSDate has an instance method timeIntervalSinceDate: that returns an NSTimeInterval.
When the first button is pressed, you can get the current data using [NSDate date] and store it in a property named 'previousDate', and then when the second button is pressed: You can get the current data again and calculate the time interval that passed using the following code:

- (void)firstButtonTapped {
    [self setPreviousDate:[NSDate date]];
}

- (void)secondButtonTapped {
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:[self previousDate]];
    // timeInterval now contains the amount of time that passed in seconds
}
s1m0n
  • 7,825
  • 1
  • 32
  • 45
  • Do i create the timer using NSDate though? Could you give me an example with code that will preform the tasks i mentioned. Thanks – 4GetFullOf Sep 13 '13 at 19:18
  • No you set the *previousDate* variable on the first button click; this is a property you store locally in your class. Then when the second button is clicked you create a new date, as shown above, and compare the two and the timeInterval will return the number of seconds that have passed. – IanStallings Sep 13 '13 at 19:42
  • i dont understand the setPreviousDate part.. cant i do something like NSDate *date2 = timeIntervalSinceDate. Look at my code above. – 4GetFullOf Sep 13 '13 at 19:44
  • Im not creating any classes – 4GetFullOf Sep 13 '13 at 19:46