问题
How can I show a countdown in HH:mm:ss format from NOW to a desired NSDate that will happen in the future?
回答1:
You have to use a timer for ticking the date.
Store a future date, and keep on substracting future date - [nsdate today]...
Calculate the time in seconds and calculate it into Hours, minutes, seconds...
//Make two properties 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];
This will come handy for you...kindly check the project...
回答2:
Start at the 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];
}
}
回答3:
Give this code a shot:
NSTimer* timer= [NSTimer scheduledTimerWithInterval: [self.futureDate timeIntervalSinceNow] target: self selector: @selector(countdown:) userInfo: nil, repeats: YES];
The countdown: method:
- (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);
}
来源:https://stackoverflow.com/questions/14406002/nsdate-countdown-from-now-to-nsdate