0

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

I am interested in printing the playback duration of a media item like '1 hour' or '2 minutes 10 seconds' depending on how large the NSTimeInterval is (without having a fixed format). Poorly there isn't any class provided by Cocoa Touch.

Before wasting time with reinventing the wheel I want to ask if somebody can recommend me an implementation of that. I am sure this is something often used, but I can't find any library/snippet which provide such a functionality on the web.

Community
  • 1
  • 1
miho
  • 11,765
  • 7
  • 42
  • 85
  • 1
    possible duplicate of [How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?](http://stackoverflow.com/questions/1237778/how-do-i-break-down-an-nstimeinterval-into-year-months-days-hours-minutes-an) or possibly [Fuzzy date algorithm](http://stackoverflow.com/questions/1052951/fuzzy-date-algorithm-in-objective-c) – jscs Aug 13 '12 at 19:05

1 Answers1

1

You could do something like this:

- (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; 
}

Punctuate and format to taste.

JacobFennell
  • 458
  • 6
  • 12
  • I am sure that will work, but I hoped their will be a some mature library for doing that. :/ – miho Aug 13 '12 at 22:08