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.
To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds.
To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).
strftime('%H:%M:%S', time. gmtime(864001)) return a nasty surprise.
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) }
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With