Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display seconds using nstimer?

I am working on a game project. I need to know that how can I display the seconds when game is started to the end of game ? also need to display in format of " 00:01 " . additional if time goes to beyond the 60 min than it should also display the hours " 1:00:01 "

any guidance ?

Thanks...

like image 581
Maulik Avatar asked Nov 20 '25 08:11

Maulik


1 Answers

After combining the answers of Nathan and Mark the complete timer method could look something like this:

- (void)timer:(NSTimer *)timer {
    NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];

    NSInteger seconds = secondsSinceStart % 60;
    NSInteger minutes = (secondsSinceStart / 60) % 60;
    NSInteger hours = secondsSinceStart / (60 * 60);
    NSString *result = nil;
    if (hours > 0) {
        result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    }
    else {
        result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];        
    }
    // set result as label.text
}

when you start the game you set the startDate and start the timer like this:

self.startDate = [NSDate date];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];

when stopping the game you use this:

self.startDate = nil;
[timer invalidate];
timer = nil;
like image 149
Matthias Bauch Avatar answered Nov 22 '25 00:11

Matthias Bauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!