Lua 如何重新格式化日期?

我目前以 2020-09-23T09:03:46.242Z (YYYY-MM-DDThh:mm:ss.sssZ) 的格式检索日期,而我试图将其转换为 Wed Sep 23 09:03:46 2020。我在字符串操作方面遇到了困难,有人有什么想法吗? 本质上,我的目标是能够对日期执行 os.time(),但我知道我可能需要做一些重新格式化。

非常感谢任何帮助

谢谢,Scott。

点赞
用户1847592
用户1847592
-- 将字符串时间转换成本地时间并输出
local s = '2020-09-23T09:03:46.242Z'
local t = {}
-- 按照时间格式提取出年月日时分秒
t.year, t.month, t.day, t.hour, t.min, t.sec = assert(s:match'^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)')
-- 将时间表转换成时间戳,并格式化输出
print(os.date('%c', os.time(t)))
2020-09-25 13:24:40
用户6632736
用户6632736

尝试这个:

local function convert (s)
    local source_format = '(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)%.'
    local year, month, day, hour, min, sec = string.match( s, source_format )
    local unix_time = os.time {
        year    = tonumber(year),
        month   = tonumber(month),
        day     = tonumber(day),
        hour    = tonumber(hour),
        min     = tonumber(min),
        sec     = tonumber(sec)
    }
    local target_format = '%a %b %d %H:%M:%S %Y'
    return os.date( target_format, unix_time )
end
2020-09-25 13:37:29