1

So I have an NSTimer and im using a date formatter to pause and play the timer but when i start the timer it starts at 07:00:00 when i want it to start at 00:00:00.

My timer code is

-(void) updateTimer {

    NSDate *currentDate = [NSDate date];

    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"hh:mm:ss";
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    hhmmssLabel .text = timeString;
    pauseTimeInterval = timeInterval;

}

-(void)pauseTimer {

    [tickerTimer invalidate];
    tickerTimer = nil;
    [self updateTimer];
}

-(void) unPauseTimer {

    startDate = [NSDate date] ;
    startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
    tickerTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}

Im assuming it has to do with the time zone so i commented it out which didnt help. I can't get it to start at 00:00:00

Robert
  • 37,670
  • 37
  • 171
  • 213
inVINCEable
  • 2,167
  • 3
  • 25
  • 49
  • Yes, it almost certainly has to do with timezone. – Hot Licks Jun 25 '13 at 14:59
  • Do you want the timer to start at midnight local time? – Black Frog Jun 25 '13 at 15:13
  • @BlackFrog I want it to start when the unPauseTimer function is called – inVINCEable Jun 25 '13 at 15:29
  • I am now reading your question. To convert NSTimeInterval to HH:mm:ss just [follow this answer](http://stackoverflow.com/questions/4933075/nstimeinterval-to-hhmmss). I would not keep track of pause time in the update timer. I will write a more detail answer below. – Black Frog Jun 25 '13 at 16:49

1 Answers1

1

I think you can simplify you code a litte. Your requirements are not too complicated (you are just dealing with intervals not absolute dates), so it would be ok to use something like this:

NSDate * currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];

// NSTimeInterval is in measured in Seconds
NSInteger hours = ( (NSInteger) timeInterval / 3600.0 );
NSInteger mins  = ( (NSInteger) (timeInterval / 60) % 60 );
NSInteger secs  = ( (NSInteger) timeInterval % 60.0 );

NSString * timeString = [NSString stringWithFormat:%02u:%02u:%02u, hours, mins, secs];

Otherwise try to look at this answer. Perhapse you need @"HH:mm:ss" (for 24 hour time) or [NSTimeZone timeZoneWithName:@"UTC"]];

Community
  • 1
  • 1
Robert
  • 37,670
  • 37
  • 171
  • 213