How can I format into Minutes:Seconds:Milliseconds from using tick()?

So I wanted to make a timer and I need to know how I can easily format the time into the format I put in the title.

How I would get the time:

local startTime

script.Parent.Start.MouseButton1Click:Connect(function()
	startTime = tick() -- sets the starting time
	script.Parent.Stop.MouseButton1Click:Connect(function()
		if startTime ~= nil then
			local timeTook = tick() - startTime -- gets the time it took for this function to happen
			print(timeTook)
			startTime = nil
		end
	end)
end)

If anyone knows how I can use the number and format it into M:S.MS please help out.

2 Likes

This is something I used! Its a Unix Time Converter! You put the Unix Time In and it countdowns the amount of time left! Countdown - Roblox

Just do some division.

local timeTook = tick() - startTime

local minutes = math.floor(timeTook / 60)
timeTook = timeTook - (minutes * 60)

local seconds = math.floor(timeTook)
timeTook = timeTook - seconds

local milliseconds = math.floor(timeTook * 1000)
print(string.format("%d:%d.%d", minutes, seconds, milliseconds))
10 Likes

Doesn’t tick() give you seconds (as opposed to milliseconds)?

Small suggestion: use "%d:%.02d.%.03d" as your format string to pad the numbers

4 Likes

It gives you the unit in seconds, but it returns a decimal number with precision up to milliseconds. For example, it might return 1595350000.1234

2 Likes

Oops. My bad. So it does.

Just to throw another suggestion out there. This one doesn’t reassign timeTook. However, it uses the modulus operator (%) and will roll over to ‘0’ after an hour which may not be desirable.

local timeTook = tick() - startTime
local minutes = (math.floor(timeTook) / 60) % 60
local seconds = math.floor(timeTook) % 60
local milliseconds = (timeTook % 1) * 1000

print(string.format("%d:%.02d.%.03d", minutes, seconds, milliseconds))

what is startTime = to?? im confusedd on that