Page 1 of 1

Convert milliseconds to human readable format

Posted: Wed Jan 30, 2013 11:48 pm
by demonnic
This came up in IRC today, and since I spent the time to throw together the function I figured I may as well share it. It takes in milliseconds as an integer, and returns a formated string in the form of HH:MM:SS:mmm . So passing in 1234 would result in 00:00:01:234. this could fairly easily be edited to not show hours by changing the return line to:
Code: [show] | [select all] lua
  return string.format("%02d:%02d:%03d",  minutes, seconds, milliseconds)  
Since I suppose most folks don't make it into hours by milliseconds generally. If nothing else, it should be a good starting off point for folks trying to format their millisecond stopwatch times and the like.

Code: [show] | [select all] lua
function milliToHuman(milliseconds)
  local totalseconds = math.floor(milliseconds / 1000)
  milliseconds = milliseconds % 1000
  local seconds = totalseconds % 60
  local minutes = math.floor(totalseconds / 60)
  local hours = math.floor(minutes / 60)
  minutes = minutes % 60
  return string.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, milliseconds)  
end

Re: Convert milliseconds to human readable format

Posted: Thu Jan 31, 2013 4:27 am
by kevutian
I wrote a function for this a few weeks ago and gave it to Vadi. I went with the fmod() option.

Re: Convert milliseconds to human readable format

Posted: Thu Jan 31, 2013 4:50 am
by demonnic
Part of what I wanted to do with it was make something that'd be somewhat easy to pick apart for new scripters. The person requesting it didn't seem to have any idea where to start, so this seemed one of the easier ways to go about it and still leave it easily customizable.

That having been said, where's the code?! =)

Re: Convert milliseconds to human readable format

Posted: Thu Jan 31, 2013 5:58 am
by kevutian
Hopefully he has it somewhere. I never kept it as it was just written out of boredom, heh.

Re: Convert milliseconds to human readable format

Posted: Fri Mar 01, 2013 3:31 pm
by kevutian
Totally thought I lost this, but it was finally located amongst a bunch of about 100 profiles, heh.
Code: [show] | [select all] lua
function shms(seconds, bool)
	assert(type(seconds) == "number", "Assertion failed for function 'shms' - Please supply a valid number.")
	if bool then assert(type(bool) == "boolean", "Assertion failed for function 'shms' - Boolean required.") return nil end
  
	local s  = seconds
	local ss = string.format("%02d", math.fmod(s, 60))
	local mm = string.format("%02d", math.fmod((s / 60 ), 60))
	local hh = string.format("%02d", (s / (60 * 60)))
	if bool then
		cecho("<green>" .. s .. " <grey>seconds converts to: <green>" .. hh .. "<white>h,<green> " .. mm .. "<white>m <grey>and<green> " .. ss .. "<white>s.")
	else
		return ss, mm, hh
	end

	collectgarbage("collect")
end