2

The task at hand is pretty simple — convert NSTimeInterval to NSString that looks like 12:34:56 (for 12 hours, 34 minutes and 56 seconds).

Max Yankov
  • 12,551
  • 12
  • 67
  • 135

1 Answers1

10

Here's a faster version of @golegka's answer:

NSString *stringFromInterval(NSTimeInterval timeInterval)
{
#define SECONDS_PER_MINUTE (60)
#define MINUTES_PER_HOUR (60)
#define SECONDS_PER_HOUR (SECONDS_PER_MINUTE * MINUTES_PER_HOUR)
#define HOURS_PER_DAY (24)

    // convert the time to an integer, as we don't need double precision, and we do need to use the modulous operator
    int ti = round(timeInterval);

    return [NSString stringWithFormat:@"%.2d:%.2d:%.2d", (ti / SECONDS_PER_HOUR) % HOURS_PER_DAY, (ti / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR, ti % SECONDS_PER_MINUTE];

#undef SECONDS_PER_MINUTE 
#undef MINUTES_PER_HOUR
#undef SECONDS_PER_HOUR
#undef HOURS_PER_DAY
}

This doesn't mess around with NSCalendars, it just uses straight integer math.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201