How can I convert seconds into hours:minutes:seconds?

I am making a limited time item for my game, so I made a script where I can put in a time, and it will count down to that on a global scale. That’s working well, but I want it to display something like 5 hours, 30 minutes, 12 seconds instead of 19812. Does anyone know how I could calculate this every repetition in the loop?

while task.wait(1) do
	seconds = math.abs(os.difftime(os.time(),os.time({year=2023, month=8, day=13, hour=0, min=40, sec=0})))
	print(seconds)
	if seconds == 0 then print("Item is offsale") break end
end

You can just do some simple math like this:

hours = math.floor(seconds/3600)
minutes = math.floor(seconds/60) - hours*60
seconds = seconds - hours*3600 - minutes*60 

Just to add on, to display it properly you would do something like

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

Thanks for the help guys this was exactly what I was looking for! It’s working now.

local function Format(n: number): string -- turns 60 into 00:01:00
	return os.date("!%X", n)
end

local function Format2(n: number): string -- turns 60 into 00h 01m 00s
	local i = 0
	return os.date("!%X", n):gsub(":", function(c) i += 1 return i == 1 and "h " or "m " end) .. "s"
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.