ammy1 ammy1 - 7 months ago 28
iOS Question

How to start a timer from zero in iOS

I have a button on which i have placed a UITapGestureRecognizer. When i tap on that button, i call a method that starts the time.
My question is, i am able to get the timer string on a label. But the timer starts from current date-time, and i want to start the timer always from zero(like a countdown timer). Here below is my code for timer.

if (gestureRecognizer.state==UIGestureRecognizerStateBegan) {

[label setHidden:NO];

if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
[label setHidden:YES];

if ([_timer isValid]) {
[_timer invalidate];
_timer = nil;


- (void)_timerFired:(NSTimer *)timer {

NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"mm:ss:SSS"];

NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
[label setText:dateInStringFormated];

Please can anyone suggest me the solution. Any help is appreciated.


Your code should be like,

 NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"mm:ss:SSS"];

NSString *dateInStringFormated=[dateformatter stringFromDate:[dateformatter dateFromString:@"00:00:000"]];
NSLog(@"test : %@",dateInStringFormated);

I have just chage [NSDate dateWithTimeIntervalSinceNow:0] with [dateformatter dateFromString:@"00:00:000"].

It will start with zero always.

Update :

I think you want something like timer that update minutes,seconds and milliseconds as i understand your question now. You can achieve it something like,

Schedule timer like,

   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

Now your updateTimer should be like,


 static double counter = 0;

 static int counter2 = 0;

int seconds = (int)counter % 60;
int minutes = ((int)counter / 60) % 60;

NSLog(@"%02d:%02d:%03d",minutes,seconds,counter2); // This should be your labels text that updating continuously

counter = counter + 0.01;

if (counter2 == 100) {
    counter2 = 0;

Hope this will help :)