如何使用 Lua 获取时区偏移量(例如:UTC+05:30)

在 Lua 中,我想将系统的时区偏移量值(例如:UTC+05:30)存储到 Lua 变量中

请帮助我使用 Lua 中的任何内置函数、自定义函数、通过从 Lua 运行 PowerShell 命令或其他方式来获取此值。我想将时区值存储到一个 Lua 变量中以供以后使用。

原文链接 https://stackoverflow.com/questions/69441967

点赞
stackoverflow用户13924341
stackoverflow用户13924341
-----------------------------------------------------------------
-- 计算本地时间与 UTC 之间的秒差。
-----------------------------------------------------------------
function get_timezone_diff_seconds()
  local now = os.time()
  return os.difftime(now, os.time(os.date("!*t", now)))
end
------------------------------------------------------------------------------------
-- 时区偏移量。例如:UTC-08:00
-- 以 ISO 8601:2000 标准形式返回时区字符串(UTC+hh:mm 或 UTC-hh:mm)
------------------------------------------------------------------------------------
function get_timezone_offset()
    local timezone_diff_seconds = get_timezone_diff_seconds()
    local h, m = math.modf(timezone_diff_seconds / 3600)
    local timezone_offset = ""

    if(timezone_diff_seconds > 0) then
        -- 以 '+' 符号作为前缀
        timezone_offset = string.format("UTC%+.2d:%.2d", h, math.abs(60 * m))
    else
        if(h == 0) then
            -- 以 '-' 符号作为前缀
            timezone_offset = string.format("UTC-%.2d:%.2d", h, math.abs(60 * m))
        else
            -- 此处 h 为负数,因此 '-' 符号是由 h 前缀的
            timezone_offset = string.format("UTC%.2d:%.2d", h, math.abs(60 * m))
        end
    end

    return timezone_offset
end
2021-11-01 16:03:54