In my Roblox place, I want to get a value representing the current time which is consistent across all running servers and places in my game.
I already know about the Time function, but the documentation for that function seems to indicate that it is only consistent across a single place (or perhaps only a single place instance?):
Returns returns the current place time in seconds.
There's also tick:
Returns the time in UNIX time, which is the number of seconds since the Unix epoch, January 1st, 1970.
But that has another issue:
Because some servers run in different timezones (such as servers in America and Europe), tick() will return a different time on those servers. This time will differ in several hours, as much as the time zone difference is. Due this fact, it cannot say anything about relative times between two servers (such as measuring how long it has taken since the last visit of the player).
How do I get a time value that's consistent across all servers and places in my game? (The actual time in real life would work well for this purpose.)
Because the ROBLOX servers can use different timezones, you would simply want to use a server where you know what timezone it uses.
To get data from an external server you need to use the HttpService.
If you have your own server, you can use that to get the current time, and if not you can look for a server that can give you the current time.
Here is an example on how you can get the current time:
local TimeServer = "http://www.timeapi.org/utc/now?%25Q"
local CurrentTime = Game:GetService("HttpService"):GetAsync(TimeServer, true)
local ServerTime = tick()
This will make the "CurrentTime" variable contain the current microseconds since Unix Epoch.
You do not want to use HttpService each time you want the time, so you want to use something like this:
function getTime()
return CurrentTime - (ServerTime * 1000) + tick()
end
But to make it more efficient, place this in a ModuleScript in Game.ServerScriptService called "Time" :
local TimeServer = "http://www.timeapi.org/utc/now?%25Q"
local CurrentTime = tonumber(Game:GetService("HttpService"):GetAsync(TimeServer, true))
local ServerTime = tick()
return function() return (CurrentTime / 1000) - ServerTime + tick() end
Then you can use it in any script like this:
local getTime = require(Game.ServerScriptService.Time)
print(getTime())
wait(1)
print(getTime())
To be noted is that if you call the tick() function from a LocalScript, you will get the player's time, and not the server's. This might not be what you normally want, but it can be used to find what timezone the player is in, or to see what the player's current time is.