iphone - NSTimeInterval 到 HH :mm:ss?

如果我有一个设置为 200.0 的 NSTimeInterval,有没有办法将其转换为 00:03:20,我想我可以用它初始化一个 NSDate,然后使用 HH:mm:ss 使用 NSDateFormatter。我的问题是,有没有一种快速的方法可以做到这一点,还是我必须自己分解数字并使用 [NSString stringWithFormat: %02d:%02d:%02d, myHour, myMin, mySec] ?

最佳答案

不需要使用 NSDateFormatter 或除除法和模数以外的任何东西。 NSTimeInterval 只是一个包含秒数的 double 。

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

https://stackoverflow.com/questions/4933075/

相关文章:

objective-c - 值/对象的 NSDictionary 键?

objective-c - 在 Objective-C 中将所有文本转换为小写

ios - 在自动布局中将 subview 的 X 居中抛出 "not prepared for t

objective-c - sizeWithFont 方法已弃用。 boundingRectWith

ios - UITableView 中的圆形 UIImageView 没有性能影响?

objective-c - 我不想在开始更新、结束更新 block 中为 uitableview 设

objective-c - Xcode 不断要求输入密码以使用系统钥匙串(keychain)

ios - AFNetworking 发布请求

objective-c - 标题中有两行文本的 UIButton (numberOfLines=2)

objective-c - 如何使用 AFNetworking 设置超时