Hello, currently I’m creating a simple script to detect and print how long a player has been in-game for, however when it goes to print when the player leaves, it prints an inaccurate and negative number. It’s counting in minutes and hours, here’s the code.
local timeclock = {}
players.PlayerAdded:Connect(function(plr)
local hour_plrtime = os.date("!*t").hour
local min_plrtime = os.date("!*t").min
timeclock[plr.UserId] = {hour_plrtime,min_plrtime}
end)
players.PlayerRemoving:Connect(function(plr)
local hour_endtime = os.date("!*t").hour
local hour_starttime = timeclock[plr.UserId][1]
local min_endtime = os.date("!*t").min
local min_starttime = timeclock[plr.UserId][2]
local hours = os.difftime(hour_starttime,hour_endtime)
local minutes = os.difftime(min_starttime,min_endtime)
if minutes == 0 and hours == 0 then return false end
if minutes <= 5 and hours == 0 then return false end
print(hours,minutes)
An example of an output I just got was
Output:
0
-1
I’m just wondering why it’s putting a negative number for the minutes and would probably do the same for the hours.
Well, another way you could go about it is creating a numbervalue when a player joins and have it add 1 per second a player is in-game. Have it do a loop like
repeat
wait(1)
p.Time.Value = p.Time.Value +2
until
p.Left == true
print(p.Time.Value)
(obviously that script is just a dummy example, please don’t use it standalone)
I’d recommend logging os.time(), not the minute/hour because that’s inaccurate if a day passes while in game.
Using os.time(), you can just do math.abs(starttime - os.time()) and divide the value by 60 to get minutes, and 60 again to get hours.
What you can do is use tick() then covert into Hours Minute Seconds If you wish:
function Format(Int)
return string.format("%02i", Int)
end
function convertToHMS(Seconds)
local Minutes = (Seconds - Seconds%60)/60
Seconds = Seconds - Minutes*60
local Hours = (Minutes - Minutes%60)/60
Minutes = Minutes - Hours*60
return Format(Hours)..":"..Format(Minutes)..":"..Format(Seconds)
end
local Log = {}
game.Players.PlayerAdded:Connect(function(Player)
Log[Player] = tick()
end)
game.Players.PlayerRemoving:Connect(function(Player)
print(Player.Name.." has been in game for "..tick() - Log[Player].." OR "..convertToHMS(tick() - Log[Player]))
end)