The countdown does not show the remaining time correctly

Hi, I am trying to create a countdown but it does not show the remaining time correctly. It is 3 hours in advance. I tried to change the targetTime but it didn’t work either, I had the same problem.

local RunService = game:GetService("RunService")

local targetTime = os.time({year = 2022, month = 1, day = 1, hour = 0, min = 0, sec = 0})
local connection

connection = RunService.RenderStepped:Connect(function()
	local delta = targetTime - os.time()
	if delta >= 0 then
		local seconds = math.floor(delta) % 60
		local minutes = math.floor(delta / 60) % 60
		local hours = math.floor(delta / 60 / 60) % 24
		local days = math.floor(delta / 60 / 60 / 24)
		script.Parent.SecondsText.Text = seconds
		script.Parent.MinutesText.Text = minutes
		script.Parent.HoursText.Text = hours
		script.Parent.DaysText.Text = days
	else
		script.Parent.SecondsText.Text = 0
		script.Parent.MinutesText.Text = 0
		script.Parent.HoursText.Text = 0
		script.Parent.DaysText.Text = 0
		connection:Disconnect()
	end
end)

This seems to work for me, I assume your issue occurs because you don’t subtract the days/hours/seconds from delta time:

local target = os.time({year = 2022, month = 1, day = 1, hour = 0, min = 0, sec = 0})
local current = tick()

local diff = os.difftime(target, current)

local days = math.floor(diff/86400)
diff -= days*86400
local hours = math.floor(diff/3600)
diff -= hours*3600
local minutes = math.floor(diff/60)
diff -= minutes*60
local seconds = diff 

print(days, hours, minutes, seconds)

Hi, that didn’t work either, it shows the same as my current code. it is in a localscript and should show the time remaining in the player’s local time.

he means that you don’t using the os.difftime() function to distinguish time

Try this code:

local RunService = game:GetService("RunService")

local targetTime = os.time({year = 2022, month = 1, day = 1, hour = 0, min = 0, sec = 0})
local connection

connection = RunService.RenderStepped:Connect(function()
	local delta = os.difftime(targetTime, os.time())
	if delta >= 0 then
		local seconds = delta % 60
		local minutes = math.floor(delta / 60) % 60
		local hours = math.floor(delta / 60 / 60) % 24
		local days = math.floor(delta / 60 / 60 / 24)
		script.Parent.SecondsText.Text = seconds
		script.Parent.MinutesText.Text = minutes
		script.Parent.HoursText.Text = hours
		script.Parent.DaysText.Text = days
        print(days .. "d " .. hours .. "h " .. minutes .. "m " .. seconds .. "s")
	else
        print("end")
		script.Parent.SecondsText.Text = 0
		script.Parent.MinutesText.Text = 0
		script.Parent.HoursText.Text = 0
		script.Parent.DaysText.Text = 0
		connection:Disconnect()
	end
end)

Replace os.time() with tick() which returns the local time.

1 Like