Convert seconds into minutes and seconds
You can resolve this problem with NSMeasurement
and NSUnitDuration
. These classes require iOS 10.0+, tvOS 10.0+, macOS 10.12+ or watchOS 3.0+. The code below converts seconds to minutes and seconds.
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
Here's a better answer from 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 version:
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)
}
You will obtain minutes with :
int minutes = totalSeconds / 60;
and remaining seconds with:
int seconds = totalSeconds % 60;.
Swift
/** 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);
}