在 Lua 中获取特定的 UTC 日期和时间

作为示例,我想在 LUA 中获取(UTC)+0000 UTC日期和时间。

我知道有一些关于此的答案,但没有一个是我的答案。解决此问题的一般方法是找到本地时间,然后加上或减去UTC数,但是我不知道我的操作系统时区,因为我的程序可以在不同的位置运行,而我无法从我的开发环境获取时区。

简言之,我如何使用 LUA 函数获取 UTC 0 日期和时间?

点赞
用户7504558
用户7504558

如果您需要生成 EPG,那么:

local timestamp = os.time()
local dt1 = os.date( "!*t", timestamp )  -- UTC
local dt2 = os.date( "*t" , timestamp )  -- local

local shift_h  = dt2.hour - dt1.hour +  (dt1.isdst and 1 or 0)    -- 如果是夏令时则加 1 小时
local shift_m = 100 * (dt2.min  - dt1.min) / 60
print( os.date("%Y%m%d%H%M%S ", timestamp) ..  string.format('%+05d' , shift_h*100 + shift_m ))
2017-04-25 04:11:28
用户30900
用户30900

我计算了世界协调时间 (UTC) 与本地时间之间的差异,这里有一个简单的 Time 类,可以将这个差异应用于存储在 from_lua_time 中的 UTC 时间。通过使用 os.date('!*t', time) 在 UTC 时间上运行来取消应用偏移量。

-- 添加到本地时间以将其转换为 UTC 时间所需的秒数。
-- 我们需要手动计算偏移量,因为 lua 不会为时间戳保留时区信息。
-- 为了保证可重复性的结果,Time 类将 epoch 纳秒存储在 UTC 中。
-- 参考 https://stackoverflow.com/a/43601438/30900
local utc_seconds_shift = (function()
  local ts = os.time()
  local utc_date = os.date('!*t', ts)
  local utc_time = os.time(utc_date)
  local local_date = os.date('*t', ts)
  local local_time = os.time(local_date)
  return local_time - utc_time
end)()

-- Time 类的元表。
local Time = {}

-- 私有函数,用于创建具有正确元表设置的新时间实例。
function Time:new()
  local o = {}
  setmetatable(o, self)
  self.__index = self
  self.nanos = 0
  return o
end

-- 将 Lua 时间戳 (假设为本地时间) 和可选的纳秒时间解析为 Time 类。
function from_lua_time(lua_ts)
  -- 克隆是因为 os.time 会更改输入表。
  local clone = {
    year = lua_ts.year,
    month = lua_ts.month,
    day = lua_ts.day,
    hour = lua_ts.hour,
    min = lua_ts.min,
    sec = lua_ts.sec,
    isdst = lua_ts.isdst,
    wday = lua_ts.wday,
    yday = lua_ts.yday
  }
  local epoch_secs = os.time(clone) + utc_seconds_shift
  local nanos = lua_ts.nanosec or 0
  local t = Time:new()
  local secs = epoch_secs * 1000000000
  t.nanos = secs + nanos
  return t
end

function Time:to_lua_time()
  local t = os.date('!*t', math.floor(self.nanos / 1000000000))
  t.yday, t.wday, t.isdst = nil, nil, nil
  t.nanosec = self.nanos % 1000000000
  return t
end
2020-04-24 04:01:36