Try this:
local function format(num, digits)
return string.format("%0" .. digits .. "i", num)
end
local function parseDateTime()
local osDate = os.date("!*t")
local year, mon, day = osDate["year"], osDate["month"], osDate["day"]
local hour, min, sec = osDate["hour"], osDate["min"], osDate["sec"]
return year .. "-" .. format(mon, 2) .. "-" .. format(day, 2) .. "T" .. format(hour, 2) .. ":" .. format(min, 2) .. ":" .. format(sec, 2) .. "Z"
end
Basically, just stick the year, month, day, hour, minute, and second together according to the format’s specification. The format
function just makes sure it zero-pads it to two digits. (e.g. 2 → 02)
Edit: Here’s the reverse, for anyone curious. It just uses a string pattern and string.match
. (iso8601 → os.date table):
local function parseIso8601(date)
local year, month, day, hour, min, sec = date:match("^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z")
return {
year = year,
month = month,
day = day,
hour = hour,
min = min,
sec = sec,
}
end