How would you convert a timestamp to an ISO 8601 format (such as 2009-01-28T21:49:59.000Z
) in Lua?
I'm specifically trying to do it by using the HttpLuaModule in Nginx.
Try os.date("!%Y-%m-%dT%TZ")
or os.date("!%Y-%m-%dT%TZ",t)
if t
has the date in seconds since the epoch.
You asked to include milliseconds, so there is a little gymnastics involved because the os.date format doesn't permit milliseconds.
This works when running in Nginx (which was the context of your question)
-- 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
Note the useful date format reference here: https://developpaper.com/lua-os-date-notes/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With