Search code examples
objective-ccocoatimensstringnstimeinterval

Convert NSTimeInterval to NSString in 00:00:00 clock format


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).


Solution

  • 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.