将秒转换为分钟和秒

时间:2011-07-09 20:20:08

标签: objective-c time

如何将秒数转换为分钟和秒数?

我知道您可以将秒数转换为分钟,但我不知道如何获得余下的秒数...

int minutes = seconds / 60;

5 个答案:

答案 0 :(得分:63)

您将获得分钟:

int minutes = totalSeconds / 60;

以及剩下的秒数:

int seconds = totalSeconds % 60;.

答案 1 :(得分:27)

以下是Convert Seconds Integer To HH:MM, iPhone

的更好答案
- (NSString *)timeFormatted:(int)totalSeconds{

  int seconds = totalSeconds % 60; 
  int minutes = (totalSeconds / 60) % 60; 
  int hours = totalSeconds / 3600; 

  return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; 
}

Swift版本:

private func getFormattedVideoTime(totalVideoDuration: Int) -> (hour: Int, minute: Int, seconds: Int){
        let seconds = totalVideoDuration % 60
        let minutes = (totalVideoDuration / 60) % 60
        let hours   = totalVideoDuration / 3600
        return (hours,minutes,seconds)
    }

答案 2 :(得分:3)

您可以使用NSMeasurementNSUnitDuration解决此问题。这些类别需要iOS 10.0 +,tvOS 10.0 +,macOS 10.12+或watchOS 3.0+。下面的代码将秒转换为分钟和秒。

int seconds = 230;
NSMeasurement* measurement = [[NSMeasurement alloc] initWithDoubleValue:seconds unit:NSUnitDuration.seconds];
NSMeasurement* measurementMinutes = [measurement measurementByConvertingToUnit:NSUnitDuration.minutes];
int minutes = floor(measurementMinutes.doubleValue);
NSMeasurement* measurementMinutesWithoutSeconds = [measurement measurementBySubtractingMeasurement:[[NSMeasurement alloc] initWithDoubleValue:minutes unit:NSUnitDuration.minutes]];
int secondsRemainder = floor([measurementMinutesWithoutSeconds measurementByConvertingToUnit:NSUnitDuration.seconds].doubleValue);
NSLog(@"%d %d", minutes, secondsRemainder); // 3 50

答案 3 :(得分:2)

夫特

/** Returns the seconds as in clock format 02:24  */
    class func formatMinuteSeconds(_ totalSeconds: Int) -> String {

        let minutes = Double(totalSeconds) / 60;
        let seconds = totalSeconds % 60;

        return String(format:"%02d:%02d", minutes, seconds);
    }

答案 4 :(得分:0)

快捷键5:

格式为hh:mm:ss

的字符串
extension Float {

    var hoursMinutesSecondsFormat : String {
    let seconds = self.truncatingRemainder(dividingBy: 60).rounded(.toNearestOrAwayFromZero)
    let minutes = (self / 60).truncatingRemainder(dividingBy: 60).rounded(.toNearestOrAwayFromZero)
    let hours   = (self / 3600).rounded(.toNearestOrAwayFromZero)
    return String(format:"%02.f:%02.f:%02.f", hours,minutes, seconds);
    }
   
}