Roblox客户端脚本获取UTC时间的方法
在 Roblox 开发中,我们经常需要获取一个不受玩家本地时区影响的标准时间,即 UTC(协调世界时)。虽然在服务器上可以直接使用 os.time(),因为它本身就在一个受控的环境中运行,但在客户端,玩家的设备时区各不相同,直接获取本地时间可能会导致数据不一致。 这里记录一个从客户端获取 UTC 时间的 Lua 脚本函数,并对其原理进行简单说明。 脚本代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 TimeAbout = {} TimeAbout.GetUTC = function(add:number?) -- 如果传入的参数不是数字,则默认为 0 if type(add) ~= "number" then add = 0 end -- 获取当前本地时间戳 local currentTime = os.time() -- 使用 "!" 标记获取当前时间的 UTC 时间表 local UTC = os.date("!*t", currentTime) -- 获取当前时间的本地时间表 local localtime = os.date("*t", currentTime) -- 计算本地时间与 UTC 时间的时间差(秒) -- os.difftime 会返回两个时间戳的差值 local diff = os.difftime(os.time(UTC), os.time(localtime)) -- 将本地时间戳加上时差,得到 UTC 时间戳 local utcTime = currentTime + diff -- 返回 UTC 时间戳,并加上可选的小时偏移量 return utcTime + add * 3600 end 实现原理说明 这个函数的核心思想是计算出本地时间与 UTC 时间之间的时差,然后用这个时差来修正本地时间戳。 ...