【发布时间】:2013-12-06 13:37:32
【问题描述】:
如何在 Lua 中将时间戳转换为 ISO 8601 格式(例如 2009-01-28T21:49:59.000Z)?
我特别想通过在 Nginx 中使用 HttpLuaModule 来做到这一点。
【问题讨论】:
标签: nginx lua timestamp iso8601 date-conversion
如何在 Lua 中将时间戳转换为 ISO 8601 格式(例如 2009-01-28T21:49:59.000Z)?
我特别想通过在 Nginx 中使用 HttpLuaModule 来做到这一点。
【问题讨论】:
标签: nginx lua timestamp iso8601 date-conversion
如果t 的日期以秒为单位,请尝试os.date("!%Y-%m-%dT%TZ") 或os.date("!%Y-%m-%dT%TZ",t)。
【讨论】:
%M 应该是小写:%m 之外,这有效。答案已更新。
bad argument #1 to 'date' (invalid conversion specifier '%TZ')。固定版本:os.date("!%Y-%m-%dT%H:%M:%SZ")
您要求包含毫秒,因此涉及到一些体操,因为 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/
【讨论】:
或者你可以使用:
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
【讨论】: