I'm creating a countdown timer and I need to printout the time left (hour:minute:seconds) until a specific date. I've found how to 开发者_运维百科get the time interval between Now and the target date but I don't know how to format the time interval as a string. Does NSDateFormater work on NSTimeInterval?
NSTimeInterval
is in seconds, use divide and remainder to break it up and format (code untested):
NSString *timeIntervalToString(NSTimeInterval interval)
{
long work = (long)interval; // convert to long, NSTimeInterval is *some* numeric type
long seconds = work % 60; // remainder is seconds
work /= 60; // total number of mins
long minutes = work % 60; // remainder is minutes
long hours = work / 60 // number of hours
// now format and return - %ld is long decimal, %02ld is zero-padded two digit long decimal
return [NSString stringWithFormat:@"%ld:%02ld:%02ld", hours, minutes, seconds];
}
You would first compare two NSDate objects to retrieve the difference in seconds between the two, the NSDate method you should use is
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
Then you could simply write a function to parse the seconds into hours/minutes/seconds, for example you could use this (untested):
-(NSDictionary*)createTimemapForSeconds:(int)seconds{
int hours = floor(seconds / (60 * 60) );
float minute_divisor = seconds % (60 * 60);
int minutes = floor(minute_divisor / 60);
float seconds_divisor = seconds % 60;
seconds = ceil(seconds_divisor);
NSDictionary * timeMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:hours], [NSNumber numberWithInt:minutes], [NSNumber numberWithInt:seconds], nil] forKeys:[NSArray arrayWithObjects:@"h", @"m", @"s", nil]];
return timeMap;
}
This is code from my project:
-(NSString*)timeLeftString
{
long seconds = [self msLeft]/1000;
if( seconds == 0 )
return @"";
if( seconds < 60 )
return [NSString stringWithFormat:
pluralString(seconds,
NSLocalizedString(@"en|%ld second left|%ld seconds left", @"")), seconds];
long minutes = seconds / 60;
seconds -= minutes*60;
if( minutes < 60 )
return [NSString stringWithFormat:
NSLocalizedString(@"%ld:%02ld left",@""),
minutes, seconds];
long hours = minutes/60;
minutes -= hours*60;
return [NSString stringWithFormat:
NSLocalizedString(@"%ld:%02ld:%02ld left",@""),
hours, minutes, seconds];
}
msLeft
--- my function that returns time in milliseconds
pluralString
--- my function that provides different parts of format string depending on the value (http://translate.sourceforge.net/wiki/l10n/pluralforms)
Function returns different format for different timer values (1 second left, 5 seconds left, 2:34 left, 1:15:14 left).
In any case, progress bad should be visible during long operation
One more thought: In case that time left is "small" (less then a minute?), probably time left should not be shown --- just progress bar left to reduce interface "visual noise".
精彩评论