How can I convert seconds into minutes and seconds?
I am aware that you can convert seconds to minutes like so, but I don\'t know how I can get the remainder of seco
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 5:
String with format 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);
}
}
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);
}
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