1

所以我有一个 NSTimer,我使用日期格式化程序来暂停和播放计时器,但是当我启动计时器时,它从 07:00:00 开始,而我希望它从 00:00:00 开始。

我的计时器代码是

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

我假设它与时区有关,所以我将其注释掉,这没有帮助。我无法让它在 00:00:00 开始

4

1 回答 1

1

我认为您可以稍微简化代码。您的要求并不太复杂(您只是处理间隔而不是绝对日期),因此可以使用以下内容:

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

否则试着看看这个答案。也许您需要@"HH:mm:ss"(24 小时)或[NSTimeZone timeZoneWithName:@"UTC"]];

于 2013-06-25T18:21:02.627 回答