Search code examples
iosnsdatenstimernstimeinterval

How to store timed passed in NSDate


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];

Solution

  • 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
    }