✓ Accepted answer
Difference
The trick to saving how much time has passed is not actually a timer in the background constantly changing, but instead it's just comparing two numbers and subtracting them. These two numbers that you're comparing is the time your event started, and the current time. Subtracting the current time by the initial start time, will give you the difference.
The only thing you need to save is the time in which the timer begins, and from that point forward you'll just be subtracting the starting time, from the current time.
Appropriate time stamp
It's also important to use the appropriate time stamp when saving this data. You really shouldn't use tick for a situation like this, as tick returns local time. Instead, you should use os.time, which returns a "global" time stamp that should be the same on all systems.
Implementation
Implementing this is pretty simple. For starters, obviously we'll save the time in which we want to start our counter off. So in this example, we'll just create a data store that saves that value to a key called "ServerTime", and we'll make the comparison as soon as the server starts.
local datastore = game:GetService("DataStoreService")
local data = datastore:GetDataStore("GameData")
local serverTime = data:GetAsync("ServerTime")
if serverTime == nil then
data:SetAsync("ServerTime", os.time())
else
local difference = os.time() - serverTime
print(difference .. " seconds have passed")
if difference >= 60*5 then
print("Time up!")
end
end
Hope this helped, let me know if you have any questions.
1 comment
Thanks for the help, it works great! I do have a question, though: How would I go about resetting the time? I'm not very good at DataStores (yet).