iPhone时间间隔之间的倒数计时器

时间:2011-08-24 12:46:21

标签: iphone nsdate nstimer

我需要iPhone识别当前时间(我可以使用NSDate做得很好)并让它倒计时到下一个时间间隔,比如半小时的每半小时。示例:如果当前时间是2:12:30且间隔是每半小时,我想要在17:30开始倒计时(17分30秒),然后转到0。

欢迎代码,也欢迎一般程序设计思路。这是我开始倒计时和获取当前时间的代码:

-(void)updateCounter:(NSTimer *)theTimer {
        if(secondsLeft > 0 ){
            secondsLeft -- ;
            minutes = (secondsLeft % 3600) / 60;
            seconds = (secondsLeft % 3600) % 60;
            waitingTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
        }
        else{
            secondsLeft = 10;
        }
    }

    -(void)countdownTimer{
        //secondsLeft = minutes = seconds = 0;
        if([timer isValid])
        {
            [timer release];
        }
       // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
        //[pool release];
    }
    -(NSDate *)getCurrentTime
    {
        NSDate *now = [NSDate date];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm:ss";

        [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
        NSLog(@"The Current Time is %@",[dateFormatter stringFromDate:now]);
        //[dateFormatter release];
        NSString *currentTime = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:now]];
        currentTimeLabel.text = currentTime;
        return now;
    }

1 个答案:

答案 0 :(得分:3)

NSDate *now = [NSDate date];
int interval = 30*60; // half hour
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval); 
NSDate *nextIntervalDate =  [NSDate 
    dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];

NSLog(@"Now is %@", now);
NSLog(@"The next interval point in time is %@", nextIntervalDate);
NSLog(@"That's another %d seconds (or %02d:%02d)", 
    secondsLeft, secondsLeft/60, secondsLeft%60);