Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to days, minutes, and hours in Obj-c

In objective-c, how can I convert an integer (representing seconds) to days, minutes, an hours?

Thanks!

like image 554
higginbotham Avatar asked Feb 21 '09 03:02

higginbotham


People also ask

How do you convert seconds to days and minutes?

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.

How do you convert seconds to hours and 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.


2 Answers

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.

like image 53
fish Avatar answered Oct 05 '22 20:10

fish


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

like image 25
Amr Faisal Avatar answered Oct 05 '22 18:10

Amr Faisal