【发布时间】:2011-08-24 12:46:21
【问题描述】:
我需要 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;
}
【问题讨论】:
-
我想过用 TimeIntervalSinceDate 从另一个中减去一个时间,但这需要添加所有潜在的间隔
-
更具体地说,我只想规定所需的时间间隔,每 10 分钟或每小时一次,然后倒计时。
-
你知道时间间隔对吗?那么你使用 TimeIntervalSinceDate 吗?
-
只需放置一个标签,使用 NSTimer 通过将计时器间隔设置为 1 每秒更新标签值。
-
如果有人在 2:15:30 按下按钮,而另一个使用该应用程序的人在 2:17:30 按下按钮,我希望两个计时器都倒计时到 2:30:00。更新倒计时不是问题,它让手机知道如果间隔是每 30 次,则分别只倒计时 14:30 和 12:30。