1

如何以 HH:mm:ss 格式显示从现在到将来会发生的所需 NSDate 的倒计时?

4

3 回答 3

5

文档开始。

NSDate *future = // whatever

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];

- (void)updateCounter:(NSTimer *)tmr
{
    NSTimeInterval iv = [future timeIntervalSinceNow];
    int h = iv / 3600;
    int m = (iv - h * 3600) / 60;
    int s = iv - h * 3600 - m * 60;
    aUILabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", h, m, s];
    if (h + m + s <= 0) {
        [tmr invalidate];
    }
}
于 2013-01-18T19:30:21.723 回答
4

您必须使用计时器来标记日期。

存储未来日期,并继续减去未来日期 - [nsdate today]...

以秒为单位计算时间,并将其计算为小时、分钟、秒...

//创建两个属性NSDate *nowDate, *futureDate

futureDate=...;

nowDate=[NSDate date];

long elapsedSeconds=[nowDate timeIntervalSinceDate:futureDate];
NSLog(@"Elaped seconds:%ld seconds",elapsedSeconds);

NSInteger seconds = elapsedSeconds % 60;
NSInteger minutes = (elapsedSeconds / 60) % 60;
NSInteger hours = elapsedSeconds / (60 * 60);
NSString *result= [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minutes, seconds];

这对你来说很方便......请检查项目......

于 2013-01-18T19:27:45.277 回答
2

试一下这段代码:

NSTimer* timer= [NSTimer scheduledTimerWithInterval: [self.futureDate timeIntervalSinceNow] target: self selector: @selector(countdown:) userInfo: nil, repeats: YES];

倒计时:方法:

- (void) countdown: (NSTimer*) timer
{
    if( [self.futureDate timeIntervalSinceNow] <= 0)
    {
        [timer invalidate];
        return;
    }
    NSDateComponents* comp= [ [NSCalendar currentCalendar] components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit startingDate: [NSDate date] toDate: self.futureDate options: 0];
    NSLog(@"%lu:%lu:%lu", comp.hour,comp.minute.comp.second);
}
于 2013-01-18T19:43:49.313 回答