因为 ROBLOX 服务器可以使用不同的时区,所以您只需要使用一个知道它使用哪个时区的服务器。
要从外部服务器获取数据,您需要使用HttpService。
如果您有自己的服务器,则可以使用它来获取当前时间,如果没有,您可以寻找可以为您提供当前时间的服务器。
以下是有关如何获取当前时间的示例:
local TimeServer = "http://www.timeapi.org/utc/now?%25Q"
local CurrentTime = Game:GetService("HttpService"):GetAsync(TimeServer, true)
local ServerTime = tick()
这将使“CurrentTime”变量包含自 Unix 纪元以来的当前微秒。
你不想每次都使用HttpService ,所以你想使用这样的东西:
function getTime()
return CurrentTime - (ServerTime * 1000) + tick()
end
但为了提高效率,请将其放在Game.ServerScriptService中名为 "Time" 的 ModuleScript 中:
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
然后您可以在任何脚本中使用它,如下所示:
local getTime = require(Game.ServerScriptService.Time)
print(getTime())
wait(1)
print(getTime())
需要注意的是,如果您从LocalScript调用tick()函数,您将获得玩家的时间,而不是服务器的时间。这可能不是您通常想要的,但它可用于查找玩家所在的时区,或查看玩家的当前时间。