Timestamp to ISO 8601 in Lua

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/