如何以HH显示倒计时:mm:ss格式从现在开始到将来会发生的所需NSDate?
答案 0 :(得分:5)
从documentation开始。
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];
}
}
答案 1 :(得分:4)
您必须使用计时器来勾选日期。
存储未来日期,并继续减去未来日期 - [今日nsdate] ...
以秒计算时间并将其计算为小时,分钟,秒......
//制作两个属性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];
这对你来说很方便...... kindly check the project ......
答案 2 :(得分: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);
}