DataStore Monthly Reset

I’m trying to create a monthly leaderboard that resets the value for the leaderboard every month

local dateTable = os.date("*t", os.time())
local keyForMonth = "Y:"..dateTable["year"].." M:"..dateTable["month"]

local dataStoreService = game:GetService("DataStoreService")
local LeaderboardDataStore = dataStoreService:GetDataStore("LeaderboardDataStore" .. keyForMonth)

game.Players.PlayerAdded:Connect(function(player)

    local Leaderboard = Instance.new("IntValue",player)
    Leaderboard.Name = "Leaderboard"
    
    if player.Leaderboard.lastTimeDataStored ~= keyForMonth then
        player.Leaderboard.Value = 0
        player.Leaderboard.lastTimeDataStored = keyForMonth
    end
    
    local data 
    local success,errormessage = pcall(function()
        data = LeaderboardDataStore:GetAsync(player.UserId.."-Leaderboard")
    end)
    if success then
        Leaderboard.Value = data
    else
        print("There was an error while getting data")
        warn(errormessage)
    end
end)
game.Players.PlayerRemoving:Connect(function(player)
    local success,errormessage = pcall(function()
        LeaderboardDataStore:SetAsync(player.UserId.."-Leaderboard",player.Leaderboard.Value)
    end)
    if success then
        print("Data successfully saved!")
    else
        print("There was an error when saving data!")
        warn(errormessage)
    end
end)

How could I change/modify this, or would it even work at all?

Just use a time function and wait a month and change the name of the data store automatically or just wipe all the data… tbh I don’t know what your planning with this but resetting datastore will make players mad and potentially ruin the game but it your game.

Try this function.

function HasDayPassed(LastTick)
    return (tick() - LastTick) >= 2592000 --// 2592000 seconds are in a month of 30 days
end

When you go to save the data just add a unique time identifer to the key. You can get the current time with os.time() and from there you get the current Month & Year. And then save that inside of the key alongside the player id. And then when you go to get the data for the datastore just use that month’s Month Number & Year.

I’m just gonna link this resource that explains the process, and as a suggestion to always search around before making posts.

When I call this function what should I put in the (LastTick) part?

Your last saved tick.

So basically like so:

function HasMonthPassed(LastTick)
    return (tick() - LastTick) >= 2592000 --// 2592000 seconds are in a month of 30 days
end

print(HasMonthPassed(tick()))