Lua - 将 XML 日期时间转换为 UTC 时间戳



我对lua没有太多经验,无法完成一个简单的(我认为(任务:

给定一个包含时间戳的字符串(从 XML 文件解析(,如何使用lua script将其转换为 UTC 格式的时间戳?

my_date = "2019-11-21T22:35:03.332+02:00"

基本上我想编写一个函数/脚本,当传递这样的字符串时,我会返回一个空字符串(如果无法转换(或 UTC 格式的时间戳(YYYY-MM-DD HH:MS:SS)

my_date最后一部分 ...+02:00 表示(本地(时间比 UTC 早 2 小时。

my_utc_date = "2019-11-21 20:35:03"

有几种方法可以实现您的目标。在这里,我将向您展示如何使用string.match和字符串模式来获取字符串元素。剩下的就是简单的数学了。

-- our input
local my_date = "2019-11-21T22:35:03.332+02:00"
-- we can just keep anything befor T as our date
local day = my_date:match("(.*)T")
-- now parse the UTC offset
local offsetH, offsetM = my_date:match("([%+%-]%d%d):(%d%d)")
-- apply sign to our minute offset
offsetM = offsetM * (tonumber(offsetH) > 0 and 1 or -1)
-- get time components
local h, m, s, ms = my_date:match("(%d%d):(%d%d):(%d%d).(%d%d%d)")
-- fix our and minute to get UTC
h = h - offsetH
m = m - offsetM
-- round seconds as we have microseconds in our input
s = math.floor(s + ms / 1000 + .5)
-- now put everything together with leading zeros
local my_utc_date = string.format("%s %02d:%02d:%02d", day, h, m, s)
print(my_utc_date)

最新更新