【问题标题】:Timestamp to ISO 8601 in LuaLua 中 ISO 8601 的时间戳
【发布时间】:2013-12-06 13:37:32
【问题描述】:

如何在 Lua 中将时间戳转换为 ISO 8601 格式(例如 2009-01-28T21:49:59.000Z)?

我特别想通过在 Nginx 中使用 HttpLuaModule 来做到这一点。

【问题讨论】:

    标签: nginx lua timestamp iso8601 date-conversion


    【解决方案1】:

    如果t 的日期以秒为单位,请尝试os.date("!%Y-%m-%dT%TZ")os.date("!%Y-%m-%dT%TZ",t)

    【讨论】:

    • 除了%M 应该是小写:%m 之外,这有效。答案已更新。
    • FWIW,这在 Lua 5.3.4 上的 Windows 上不起作用,产生:bad argument #1 to 'date' (invalid conversion specifier '%TZ')。固定版本:os.date("!%Y-%m-%dT%H:%M:%SZ")
    【解决方案2】:

    您要求包含毫秒,因此涉及到一些体操,因为 os.date 格式不允许毫秒。
    这在 Nginx 中运行时有效(这是您问题的上下文)

    -- Return a ISO 8061 formatted timestamp in UTC (Z)
    -- @return e.g. 2021-09-21T15:20:44.323Z
    local function iso_8061_timestamp()
        local now = ngx.now()                               -- 1632237644.324
        local ms = math.floor((now % 1) * 1000)             -- 323 or 324 (rounding)
        local epochSeconds = math.floor(now)
        return os.date("!%Y-%m-%dT%T", epochSeconds) .. "." .. ms .. "Z"  -- 2021-09-21T15:20:44.323Z
    end
    

    请注意此处有用的日期格式参考:https://developpaper.com/lua-os-date-notes/

    【讨论】:

      【解决方案3】:

      或者你可以使用:

      local now_date_time = os.date("!%Y%m%dT%H%M%S") --> For date_time: 20191015T042028Z
      
      local now_date = os.date("!%Y%m%d") --> For only date: 20191015
      

      【讨论】:

        猜你喜欢
        • 2023-04-11
        • 2013-03-11
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 2019-02-02
        • 1970-01-01
        • 2012-02-13
        • 1970-01-01
        相关资源
        最近更新 更多