In objective-c, how can I convert an integer (representing seconds) to days, minutes, an hours?
Thanks!
int seconds = (totalSeconds % 60); int minutes = (totalSeconds % 3600) / 60; int hours = (totalSeconds % 86400) / 3600; int days = (totalSeconds % (86400 * 30)) / 86400; First line - We get the remainder of seconds when dividing by number of seconds in a minutes.
In this case, the minute digits 30 are associated with the quantity one half. Converting between hours, minutes, and seconds using decimal time is relatively straightforward: time in seconds = time in minutes * 60 = time in hours * 3600. time in minutes = time in seconds / 60 = time in hours * 60.
In this case, you simply need to divide.
days = num_seconds / (60 * 60 * 24);
num_seconds -= days * (60 * 60 * 24);
hours = num_seconds / (60 * 60);
num_seconds -= hours * (60 * 60);
minutes = num_seconds / 60;
For more sophisticated date calculations, such as the number of days within the ten million seconds after 3pm on January 19th in 1983, you would use the NSCalendar class along with NSDateComponents. Apple's date and time programming guide helps you here.
try this,
int forHours = seconds / 3600,
remainder = seconds % 3600,
forMinutes = remainder / 60,
forSeconds = remainder % 60;
and you can use it to get more details as days, weeks, months, and years by following the same procedure
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