Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp to ISO 8601 in Lua

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.

like image 833
Mark Avatar asked Nov 21 '13 21:11

Mark


2 Answers

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.

like image 158
lhf Avatar answered Oct 17 '22 06:10

lhf


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/

like image 1
Paul Hilliar Avatar answered Oct 17 '22 06:10

Paul Hilliar