我没有太多经验,lua
无法完成简单的任务(我认为):
给定一个包含时间戳记的字符串(从XML文件解析),如何使用UTC将其转换为UTC格式的TIMESTAMP lua script
?
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句