How to convert milliseconds into human readable form?

FlySwat picture FlySwat · Oct 6, 2008 · Viewed 153.2k times · Source

I need to convert an arbitrary amount of milliseconds into Days, Hours, Minutes Second.

For example: 10 Days, 5 hours, 13 minutes, 1 second.

Answer

Greg Hewgill picture Greg Hewgill · Oct 6, 2008

Well, since nobody else has stepped up, I'll write the easy code to do this:

x = ms / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x

I'm just glad you stopped at days and didn't ask for months. :)

Note that in the above, it is assumed that / represents truncating integer division. If you use this code in a language where / represents floating point division, you will need to manually truncate the results of the division as needed.