Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Seconds Integer To HH:MM, iPhone

I am struggling with this. I have a value in seconds that I want to display in a label in HH:MM format. I have searched the internet for ages and found some answers, but either not fully understood them, or they seem like an odd way of doing what I want. If someone could help me out on this one that would be great! Bear in mind that I am new to this games so this question may seem like a really basic one to the more experienced out there.

like image 298
Stumf Avatar asked Nov 16 '09 00:11

Stumf


People also ask

How do you convert seconds to HH MM SS?

To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds.

How do you convert integers to seconds?

To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).

How do you convert seconds to HH MM SS in Python?

strftime('%H:%M:%S', time. gmtime(864001)) return a nasty surprise.


2 Answers

I was looking for the same thing that you are looking but couldn't find one. So I wrote one -

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

works perfectly in Swift as well:

 func timeFormatted(totalSeconds: Int) -> String {     let seconds: Int = totalSeconds % 60     let minutes: Int = (totalSeconds / 60) % 60     let hours: Int = totalSeconds / 3600     return String(format: "%02d:%02d:%02d", hours, minutes, seconds)  } 
like image 139
Rohit Agarwal Avatar answered Nov 16 '22 00:11

Rohit Agarwal


In iOS 8.0 and higher versions it can also be done with NSDateComponentsFormatter. I need to mention that it will format the string without first leading zero, for example '9:30', but not '09:30'. But if you like to use formatters, you can use this code:

-(NSString *)getTimeStringFromSeconds:(double)seconds {      NSDateComponentsFormatter *dcFormatter = [[NSDateComponentsFormatter alloc] init];      dcFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;      dcFormatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;      dcFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;      return [dcFormatter stringFromTimeInterval:seconds]; } 
like image 39
edukulele Avatar answered Nov 15 '22 22:11

edukulele