How to convert seconds into a proper timer format

if you’ve played a game that uses a core gameplay loop, chances are you’ve seen at least one game with timers that look something like this:

(cool timers, wow!)

i thought i’d set some time aside to show you how to convert seconds into the timer format.

NOTE: this is simply how to convert seconds into a timer format, you’ll have to make the timer system yourself

how this works

  • math.floor(seconds / 60) calculates the number of whole minutes in the given number of seconds.
  • seconds % 60 calculates the remaining seconds after removing the minutes.
  • the string.format() stuff formats the minutes and seconds with leading zeros if they are less than 10
local function formatTime(seconds)
	local minutes = math.floor(seconds / 60)
	local remainingSeconds = seconds % 60

	local formattedMinutes = string.format("%02d", minutes)
	local formattedSeconds = string.format("%02d", remainingSeconds)

	return formattedMinutes, formattedSeconds

--[[ this is how it ought to be used. you can replace totalSeconds with any number of 
 seconds you want to convert and the formatTime function will return the formatted minutes and seconds ]]--

local totalSeconds = 300
local formattedMinutes, formattedSeconds = formatTime(totalSeconds)
print(formattedMinutes .. ":" .. formattedSeconds)  -- this will print 05:00