How I can convert milliseconds to minutes or hours, in Objective-C or C?
Asked
Active
Viewed 1.5k times
2
-
1There's 1000 milliseconds in a second. There's 60 seconds in a minute. 966000 / 1000 => 966 / 60 => 16 minutes. – Marvo May 18 '11 at 21:18
-
2Close-as-off-topic lacks as "belongs on math.stackexchange.com" option... – R.. GitHub STOP HELPING ICE May 18 '11 at 21:19
-
possible duplicate of [Convert milliseconds to seconds in C.](http://stackoverflow.com/questions/1294885/convert-milliseconds-to-seconds-in-c) – jscs May 18 '11 at 21:27
-
1@R: I think this would get closed there as "Off-topic: programming question." – jscs May 18 '11 at 21:27
-
Are your seconds representing duration, or absolute time? Are you interested in correct handling of leap seconds? – Marc Mutz - mmutz May 18 '11 at 21:28
-
1Not a real question?! It's a perfectly valid question. It's just a dupe. – jscs May 18 '11 at 23:56
-
I believe Maxime wants to do this programmatically and it therefore is a valid question. – Eric Brotto Jul 08 '11 at 10:40
4 Answers
10
Just use simple division. Use floating point numbers so that you don't lose precision from rounding.
float milliseconds = 966000.0;
float seconds = milliseconds / 1000.0;
float minutes = seconds / 60.0;
float hours = minutes / 60.0;

ughoavgfhw
- 39,734
- 6
- 101
- 123
3
#define MSEC_PER_SEC 1000L
#define SEC_PER_MIN 60
#define MIN_PER_HOUR 60
int msec = 966000;
int min = msec / (MSEC_PER_SEC * SEC_PER_MIN);
int hr = min / (MIN_PER_HOUR);

makes
- 6,438
- 3
- 40
- 58
-
1
-
@progrmr Descriptive, but not more, as you can assume these constants to NEVER change their values in a meaningful context. – Christian Rau May 18 '11 at 22:43
-
1@Christian, magic numbers without a meaningful name are bad style, no matter if their values change in this universe or not. – makes May 18 '11 at 22:56
2
sounds a bit like a joke but what the heck…
- divide by 60*1000… for minutes.
- divide by 60*60*1000… for hours.
the beauty of it it works in all programming languages.

machunter
- 967
- 1
- 11
- 27