NSTimeInterval Formatting

后端 未结 5 902
梦谈多话
梦谈多话 2020-12-02 19:51

I want to take my NSTimeInterval and format it into a string as 00:00:00 (hours, minutes, seconds). What is the best way to do this?

5条回答
  •  北海茫月
    2020-12-02 20:53

    "Best" is subjective. The simplest way is this:

    unsigned int seconds = (unsigned int)round(myTimeInterval);
    NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
        seconds / 3600, (seconds / 60) % 60, seconds % 60];
    

    UPDATE

    As of iOS 8.0 and Mac OS X 10.10 (Yosemite), you can use NSDateComponentsFormatter if you need a locale-compliant solution. Example:

    NSTimeInterval interval = 1234.56;
    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute |
        NSCalendarUnitSecond;
    formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
    NSString *string = [formatter stringFromTimeInterval:interval];
    NSLog(@"%@", string);
    // output: 0:20:34
    

    However, I don't see a way to force it to output two digits for the hour, so if that's important to you, you'll need to use a different solution.

提交回复
热议问题