Help with seconds to M:S:Ms

Hi! I am making a speedrun game and I wan the timer to show the time in mins : secs : millisecs.
Something like in Speed Race, pretty much.

When the round starts, every map has its own map duration setting (in seconds). The timer counts down from that value until 0. However, I know that I shouldn’t (and its very random and not exact) use wait(1/1000).

There have been quite a few topics on this but none of them explain it properly. Some say to use tick() but that can tell you the time in seconds, not milliseconds and I just don’t really understand it.
I don’t need full code, but just some info and a proper explanation would really help. Thanks! :grinning:

My code below is currently showing time in H:M:S. I need a way of somehow waiting a millisecond instead to hours become minutes, etc…

function GameModule.convertTime(s)
	return string.format("%02i:%02i:%02i", s / 60 ^ 2, s / 60 % 60, s % 60)
end
	
function GameModule.ProgressLoop(TIME)
	if tonumber(TIME) then
		for i = TIME, 0, -1 do
			status.Value = GameModule.convertTime(i).." left!"
						
			wait(1)
			
			ReplicatedStorage.CurrentTime.Value = GameModule.convertTime(i)
			
			if #Teams.Playing:GetPlayers() == 0 then
				break
			end
		end
	end
end
1 Like

Just wanted to let you know before you make a terrible mistake, there are 1000 milliseconds in a second. Not 60. Notice the"milli" prefix. * (꧆▽꧆)

3 Likes

Oops messed up writing that, I do use milliseconds it’s a typo lol. Thanks for pointing it out

1 Like
> print(tick())
  1591893650.5433

tick() is a decimal number which should be enough precision for what you’re trying to do.

1 Like

If you need to calculate time left with precision, you can use tick() and a “start time” variable to get what you want.

local DURATION = 60
local startTime = tick()

game:GetService("RunService").Heartbeat:Connect(function()
   local elapsed = tick() - startTime -- how long has it been since we started
   local remaining = math.max(DURATION - elapsed, 0) -- how much do we have left, max to prevent going negative

   local convertedTime = GameModule.convertTime(remaining)
   status.Value = convertedTime.. " left!"
   CurrentTime.Value = convertedTime
end)

To calculate milliseconds, you will also need to modify the seconds value:

local minutes = math.floor(s / 60)
local seconds = s % 60
local milliseconds = (seconds * 1000) % 1000
seconds = math.floor(seconds)
return string.format("%02i:%02i:%02i", minutes, seconds, milliseconds)
6 Likes