Creating A Countdown With os.time()

Hello I am trying to create a countdown timer using os.time. It seems somewhere my math is wrong?

local SimulateTimePassed = 6973 -- How much pseudo time has 'passed' in seconds
local Before = os.time()-SimulateTimePassed
local MaxTime = 7200 -- 2 hrs in seconds

while wait(1) do
    local Elapsed = os.difftime(Before, os.time())
    
    local seconds = Elapsed % 60
    local minutes = math.floor(Elapsed % (60 * 60) / 60)
    local hours = math.floor(Elapsed % (60 * 60 * 24) / (60 * 60))

    print(hours,":",minutes,":",seconds)
end

But I keep getting stuck with a weird hour timer. I should have 0 hours left, not 22.
image

I’m sure I’m being stupid and missing something, would love some quick help!

1 Like

Here is my version of countdown.

local countdowntime = 1000 -- in seconds

local futuretime = os.clock()+countdowntime

local timeleft = futuretime

while timeleft > 1 do

timeleft = math.abs(futuretime - os.clock())

local hours = math.floor(timeleft/3600)

local hs = timeleft % 3600

local mins = math.floor(hs/60)

local secsleft = hs%60

print(hours..":"..mins..":"..math.floor(secsleft))

task.wait(0.1)

end

print("countdown done")
4 Likes

Use tick() instead.

Tick is deprecated, and os.clock is accurate to microsecond while tick is only to millisecond. So 1000x more accurate in a way…

1 Like

tick() is simpler and you’d likely never need precision to the millisecond over microsecond.

How is tick simpler? Not only does replacing tick()i in his script not do anything to actually help the person, but also it’s deprecated and should not be used for NEW work.

4 Likes