Sound isn't playing at specified time

So, the goal of this script is for the server to play Sound every day at 11:59:40 PM EST, but it’s not working and I’ve no idea why. How would I edit the code so it successfully plays the sound at the specified real world time?

local RunService = game:GetService("RunService")
local Sound = game.Workspace.Bong

local DaysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

function GetNextTimestamp()
    local Now = os.date("!*t")
    
    local NextDay = (Now.day + 1)
    local NextMonth = Now.month
    local NextYear = Now.year
    
    if NextDay > DaysInMonth[NextMonth] then
        NextDay = 1
        NextMonth += 1
        
        if NextMonth > 12 then
            NextMonth = 1
            NextYear += 1
        end
    end
    
    local Timestamp = os.time({
        year = NextYear,
        month = NextMonth,
        day = NextDay,
        hour = 23,
        min = 59,
        sec = 40,
    })
    
    return Timestamp - 5 * (60 * 60) -- EST calculations
end

RunService.Heartbeat:Connect(function()
    local NextTimestamp = GetNextTimestamp()
    
    if os.time() >= NextTimestamp then
        if not Sound.IsPlaying then
            Sound:Play()
        end
    end
end)

Wouldn’t it be simpler to check if the timeStamp is 11:59:40 PM EST everytime you want the loop to run?

It might be your date calculations are not working because the “NextTimestamp” is always before the check, or simply something went wrong, I reccomend lowering the accuracy by not using a Heartbeat but a while wait() loop, and checking the hour, minutes, and seconds, and then playing the sound.

I feel like you could dramatically simplify the code, which would also help resolve the issue.

os.time, when called from the server, will give the UTC time (assuming done out of studio). You can make use of this to detect the time:

while true do
    local TimeOfDay = (os.time() % (3600 * 24)) - 5 * 3600 -- Make it the time of day, then change it from  UTC to EST
    if TimeOfDay > (3600 * 24) - 20 then -- if its between 20 seconds and 0 seconds to midnight
        if not Sound.IsPlaying then
            Sound:Play()
        end
    end
    task.wait(1) -- If you want, you can reduce this value
end
1 Like