将动态持续时间打印到NSString的好方法

时间:2012-08-13 18:56:59

标签: objective-c ios cocoa-touch duration nstimeinterval

  

可能重复:
  Fuzzy Date algorithm in Objective-C
  How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

我有兴趣打印媒体项目的播放持续时间,例如“1小时”或“2分10秒”,具体取决于NSTimeInterval的大小(没有固定格式)。很糟糕,Cocoa Touch没有提供任何课程。

在浪费时间重新发明轮子之前,我想问一下是否有人可以推荐我实施。我确信这是经常使用的东西,但我找不到任何在网上提供这种功能的库/代码段。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

- (NSString*)timeIntervalStringforDouble:(double)timeInterval {
NSString *intervalString=@"";
NSInteger hours = (int)floor(timeInterval/3600.0);
double remainder = timeInterval-(hours*3600);
NSInteger minutes = (int)floor(remainder/60.0);
NSInteger seconds = (int)round(remainder-(minutes*60));
NSString *temporalSegment = @"hour";
if (hours) {
    if (hours>1) temporalSegment = @"hours";
    intervalString = [intervalString stringByAppendingFormat:@"%d %@ ",hours,temporalSegment];
}
if (minutes || hours) {
    temporalSegment = (minutes==1)? @"minute":@"minutes";
    intervalString = [intervalString stringByAppendingFormat:@"%d %@ ",minutes,temporalSegment];
}
if (seconds || minutes) {
    temporalSegment = (seconds==1)?@"second":@"seconds";
    intervalString = [intervalString stringByAppendingFormat:@"%d %@",seconds, temporalSegment];
}
return intervalString; 
}

标点和格式化。