Is it possible to save Time with datastore?

Hi,

I have this script in ServerScriptService that runs the hours and the day. I was wondering if it’s possible to save the time in a datastore so that players can join and leave the server and it doesn’t reset to 8o’ clock like in the script?

SSS:

local DayLength = 1440
local InitialTime = 8

local days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local RS = game:GetService("RunService")
local CurrentDay = 1
local playerList = {}
local start = tick()-(InitialTime/24*DayLength)

RS.Stepped:Connect(function()
	local t = (tick()-start)/DayLength*24
	if t >= 24 then
		start = tick()
		CurrentDay = math.fmod(CurrentDay, 7)+1
	end
	game.Lighting.ClockTime = math.fmod(t, 24)

	local hours = math.floor(t % 24)
	local minutes = math.floor((t % 24 - hours) * 60)
	local period = (hours >= 12) and "PM" or "AM"
	hours = (hours % 12)
	if hours == 0 then hours = 12 end

	for i, plr in pairs(playerList) do
		local day = plr.PlayerGui.TimeGui.Day
		local Time = plr.PlayerGui.TimeGui.Time
		day.Text = days[CurrentDay]
		Time.Text = string.format("%02d:%02d %s", hours, minutes, period) 
	end
end)

game.Players.PlayerAdded:Connect(function(plr)
	plr.PlayerGui:WaitForChild("TimeGui")
	table.insert(playerList, plr)
end)

game.Players.PlayerRemoving:Connect(function(plr)
	if table.find(playerList, plr) then
		table.remove(playerList, table.find(playerList, plr))
	end
end)
1 Like

Yes, it is possible. What time do you mean? You can save everything. With a bit math you get every result too. For a detailed info I need more I formation.

1 Like

I was hoping to save the hours/minutes and the weekday. So for example if a user leaves at 12pm on Wednesday then the time wouldn’t reset back to what the script starts with.

I’d recommend storing time as a simple number rather than storing hours and minutes separately. This is unix time, which is usually a number that has been going up by 1 every second since January 1970, and is then converted into a readable date. In your case you can just store a number that starts at 0 and goes up as the player is playing
(you don’t have to make it go up by 1 every second, you can calculate that number like so)

local TimeStart = 1000 -- Previously stored number in your datastore, or 0

local Offset = TimeStart - os.clock() -- can use os.time() or other

local function GetTime()
	return Offset + os.clock() -- Values returned by this will start at TimeStart, and return a number gradually higher as time passes
end

When saving to the datastore, save the time returned by GetTime, and when the player joins afterwards, set TimeStart to that previously saved value

1 Like