Objective-c格式到特定日期的剩余时间
我正在创建一个倒计时计时器,我需要打印出到特定日期的剩余时间(小时:分钟:秒)。我已经找到了如何获取从现在到目标日期之间的时间间隔,但我不知道如何将时间间隔格式化为字符串。NSDateFormatter在NSTimeInterval上工作吗?首先比较两个NSDate对象以获取两者之间的秒差,您应该使用的NSDate方法是Objective-c格式到特定日期的剩余时间,objective-c,nsdate,nstimeinterval,Objective C,Nsdate,Nstimeinterval,我正在创建一个倒计时计时器,我需要打印出到特定日期的剩余时间(小时:分钟:秒)。我已经找到了如何获取从现在到目标日期之间的时间间隔,但我不知道如何将时间间隔格式化为字符串。NSDateFormatter在NSTimeInterval上工作吗?首先比较两个NSDate对象以获取两者之间的秒差,您应该使用的NSDate方法是 - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate 然后,您可以简单地编写一个函数,将秒解析为小时/分
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
然后,您可以简单地编写一个函数,将秒解析为小时/分钟/秒,例如,您可以使用这个(未测试):
NSTimeInterval
以秒为单位,使用除法和余数将其分解并格式化(代码未测试):
这是我的项目中的代码:
-(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];
}
-(NSString*)timeLeftString
{
长秒=[self msLeft]/1000;
如果(秒==0)
返回@”;
如果(秒<60)
返回[NSString stringWithFormat:
复数字符串(秒,
NSLocalizedString(@“en |%ld秒左|%ld秒左,@”),秒];
长分钟=秒/60;
秒-=分钟*60;
如果(分钟<60)
返回[NSString stringWithFormat:
NSLocalizedString(@“%ld:%02ld左”,“@”),
分,秒];
长时间=分钟/60;
分钟-=小时*60;
返回[NSString stringWithFormat:
NSLocalizedString(@“%ld:%02ld:%02ld左”,“@”),
小时、分钟、秒];
}
msLeft
——以毫秒为单位返回时间的my函数
pluralString
——我的函数,它根据值提供格式字符串的不同部分(http://translate.sourceforge.net/wiki/l10n/pluralforms)
函数为不同的计时器值返回不同的格式(左1秒、左5秒、左2:34、左1:15:14)
在任何情况下,在长时间运行期间,应能看到不良进度
还有一个想法:如果剩余时间“很小”(少于一分钟?),可能不应该显示剩余时间——只需留下进度条,以减少界面的“视觉噪音”。谢谢分享。你能发布你的pluralString函数吗?这也适用于pluralString。
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];
}
-(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];
}