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

后端 未结 11 2384
[愿得一人]
[愿得一人] 2020-12-13 01:16

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

Thanks!

11条回答
  •  春和景丽
    2020-12-13 01:59

    I know this is an old post but I wanted to share anyway. The following code is what I use.

    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.

    Second line - We get the remainder of seconds after dividing by the number of seconds in an hour. Then we divide that by seconds in a minute.

    Third line - We get the remainder of seconds after dividing by the number of seconds in a day. Then we divide that by the number of seconds in a hour.

    Fourth line - We get the remainder of second after dividing by the number of seconds in a month. Then we divide that by the number of seconds in a day. We could just use the following for Days...

    int days = totalSeconds / 86400;
    

    But if we used the above line and wanted to continue on and get months we would end up with 1 month and 30 days when we wanted to get just 1 month.

    Open up a Playground in Xcode and try it out.

提交回复
热议问题