Simple Time Code

Posted by Neves on Wed 23 Feb 2011 04:49 PM — 3 posts, 16,881 views.

USA #0
I'm sure this is simple, yet it isn't working, so I am wondering if someone can help me. I want to convert a number which represents the amount of time connected in seconds to be in days, hours, minutes, seconds for a plugin in Lua script.
Assuming the variable is called time_secs and I want the final string to be called time_string, how would it be done?
One extra requirement if possible is that it will only display the time in hrs or days if it is over 1 hr or 1 day.

I was using:
time_hrs = time_secs%3600
time_mins = time_secs%60
but it didn't seem to work write.

Thanks,
Neves
(also I don't get e-mail replies to these posts, yet my e-mail is working, can that be reset?)
#1
this returns a string in the format h:m:s

function SecondsToClock(sSeconds)
  local nSeconds = tonumber(sSeconds)
  if nSeconds == 0 or nSeconds == nil then
    --return nil;
    return "00:00:00";
  elseif nSeconds < 0 then
    return tostring(sSeconds)
  else
    nHours = string.format("%02.f", math.floor(nSeconds/3600));
    nMins = string.format("%02.f", math.floor(nSeconds/60 - (nHours*60)));
    nSecs = string.format("%02.f", math.floor(nSeconds - nHours*3600 - nMins *60));
    if nHours ~= "00" then
      return nHours..":"..nMins..":"..nSecs
    else
      return nMins..":"..nSecs
    end
  end
end

or this returns the numbers and then you can put them in a string however you want to (based on a function from Nick)

function SecondsToDHMS(sSeconds)
  local nSeconds = tonumber(sSeconds)
  if nSeconds == 0 then
    return 0, 0, 0, 0
  else
    nDays = math.floor(nSeconds/(3600 * 24))
    nHours = math.floor(nSeconds/3600 - (nDays * 24))
    nMins = math.floor(nSeconds/60 - (nHours * 60) - (nDays * 24 * 60))
    nSecs = sSeconds % 60
    return nDays, nHours, nMins, nSecs
  end
end


Bast
Australia Forum Administrator #2
In commas.lua module is a function to convert seconds to roughly what you want.

I reset your email flag.