NSTimeInterval to HH:mm:ss?

后端 未结 12 1807
陌清茗
陌清茗 2020-12-04 08:53

If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFo

12条回答
  •  日久生厌
    2020-12-04 09:40

    No need to use NSDateFormatter or anything else than division and modulo. NSTimeInterval is just a double containing seconds.

    Swift

    func stringFromTimeInterval(interval: NSTimeInterval) -> String {
        let interval = Int(interval)
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let hours = (interval / 3600)
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
    }
    

    Objective-C

    - (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
        NSInteger ti = (NSInteger)interval;
        NSInteger seconds = ti % 60;
        NSInteger minutes = (ti / 60) % 60;
        NSInteger hours = (ti / 3600);
        return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds];
    }
    

提交回复
热议问题