The result is always 0

I’m making a button that calculates the time since you pressed the button for the first time but the result is always a 0.

the script:

local label = script.Parent.Parent.TextLabel
local count = 0

script.Parent.MouseButton1Click:Connect(function()
	count = count + 1
	print(count)
	local passedTime = os.time()
	print(passedTime)
	if count == 1 then
		script.Parent.Text = "press again to see the time since you pressed the button"
	end

	if count == 2 then
		print(count)
		local currentTime = os.time()
		print(currentTime)
		local exactTime = currentTime - passedTime
		print(exactTime)
		label.Text = "The time since you pressed the button was "..tostring(exactTime).. " seconds ago"
		count = 0
	end
end)

You need to put passedTime outside of the event as it doesn’t save when you click it again and saves passedTime as the current time:

local label = script.Parent.Parent.TextLabel
local count = 0
local passedTime

script.Parent.MouseButton1Click:Connect(function()
	count = count + 1
	print(count)
	if count == 1 then
		script.Parent.Text = "press again to see the time since you pressed the button"
passedTime = os.time()
	print(passedTime) -- placed in here to prevent passedTime to update when count is 2
	end

	if count == 2 then
		print(count)
		local currentTime = os.time()
		print(currentTime)
		local exactTime = currentTime - passedTime
		print(exactTime)
		label.Text = "The time since you pressed the button was "..tostring(exactTime).. " seconds ago"
		count = 0
	end
end)
1 Like

You’ll need to modify this to fit you call.

local button = script.Parent
local startTime = 0
local isRunning = false

button.Activated:Connect(function()
    if not isRunning then
        startTime = tick()
        isRunning = true
    else
        local currentTime = tick()
        local elapsedTime = currentTime - startTime

        local hours = math.floor(elapsedTime / 3600)
        local minutes = math.floor((elapsedTime % 3600) / 60)
        local seconds = math.floor(elapsedTime % 60)

        print("Time since button press: " .. hours .. "h " .. minutes .. "m " .. seconds .. "s")
        isRunning = false
    end
end)

Looks like this was solved while I still had the page up working on it … I’ll leave it for the floor calls.

1 Like

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