Help in improving incrementing clock

So I’m trying to make a clock kind of thing for my game. So what I want is that it should convert seconds into the best possible form. For example:

5s - 5s
60s - 1min
3600s - 1h
etc.

So I tried doing it with tables. But the limitation is that it works only till it reaches hours. So is there any better way of doing this:

local timeInSeconds = 1

local units = {
	("s"); -- seconds
	("m"); -- minutes
	("h"); -- hours
}


local function convertSeconds(timeInSeconds)
	local newTime = timeInSeconds
	local newUnit = ("s")
	
	local unitIndex = 2
	
	repeat
		if newTime >= 60 then
			newTime = newTime / 60
			newTime = math.floor(newTime * 100) / 100 -- this helps in getting two decimal values
			newUnit = units[unitIndex]
			
			unitIndex = unitIndex + 1
		end
		
	until newTime < 60 or unitIndex == #units + 1
	
	
	local returnValue = (tostring(newTime) .. newUnit)
	
	return returnValue
end


while wait(0.05) do
	local newTime = convertSeconds(timeInSeconds)
	print(newTime)
	
	timeInSeconds += 1
end

Any help would be appreciated. :slightly_smiling_face:

1 Like
local seconds, minutes, hours = 0,0,0
while wait(1) do
  if seconds < 60 then
    seconds += 1
  else
    if minutes < 60 then
      minutes += 1
      seconds = 0
    else
      hours += 1
      minutes = 0
      seconds = 0
    end
  end
end

This checks everytime a minute or second becomes 60 and then adds to its superior and then sets back to zero for the next count so

if seconds == 60 then minute += 1 end

Thanks a lot. Your method isn’t bad but how would I go with making it even longer, like days, weeks etc. That’s my question

Well then just add a day variable

local seconds, minutes, hours, days, weeks = 0,0,0,0,0
while wait(1) do
  if seconds < 60 then
    seconds += 1
  else
    if minutes < 60 then
      minutes += 1
      seconds = 0
    else
      if hours < 24 then
        hours += 1
        minutes = 0
        seconds = 0
      else
        if days < 7 then
          days += 1
          hours = 0
          minutes = 0
          seconds = 0
        else
          weeks += 1 
          days = 0
          hours = 0
          minutes = 0
          seconds = 0
        end
      end
    end
  end
end

You just repeat the same process but make sure to reset the inferiors when you change a value so if i changed hours remember to reset minutes and seconds

1 Like

Actually, I think that I’m thinking on it too much. So yeah, your idea is pretty good. So I guess this is pretty good enough. I was initially thinking of something that will be super efficient. But I guess this is enough for what I want.