Lua 如何将字符串时间转换为unix?
我正在创建一个管理工具,需要将Lua中的字符串类型“1y2m3d4h5mi6s”转换为unixtime(秒)。我怎么做这个Lua 如何将字符串时间转换为unix?,lua,Lua,我正在创建一个管理工具,需要将Lua中的字符串类型“1y2m3d4h5mi6s”转换为unixtime(秒)。我怎么做这个 我希望strotime(“1d”)的输出是86400将日期字符串转换为秒的代码片段 local testDate = '2019y2m8d15h0mi42s' local seconds = string.gsub( testDate, '(%d+)y(%d+)m(%d+)d(%d+)h(%d+)mi(%d+)s', function(y, mon, d, h,
我希望
strotime(“1d”)
的输出是86400
将日期字符串转换为秒的代码片段
local testDate = '2019y2m8d15h0mi42s'
local seconds = string.gsub(
testDate,
'(%d+)y(%d+)m(%d+)d(%d+)h(%d+)mi(%d+)s',
function(y, mon, d, h, min, s)
return os.time{
year = tonumber(y),
month = tonumber(mon),
day = tonumber(d),
hour = tonumber(h),
min = tonumber(min),
sec = tonumber(s)
}
end
)
print(seconds)
你也可以写一个局部函数,我觉得读起来更好
local function printTime(y, mon, d, h, min, s)
local res = os.time{
year = tonumber(y),
month = tonumber(mon),
day = tonumber(d),
hour = tonumber(h),
min = tonumber(min),
sec = tonumber(s)
}
return res
end
local testDate = '2019y2m8d15h0mi42s'
local seconds = string.gsub(
testDate,
'(%d+)y(%d+)m(%d+)d(%d+)h(%d+)mi(%d+)s',
printTime
)
print(seconds)
使用拆分字符串并使用
os.time
创建秒()。如果您需要任何进一步的帮助,我将编写一个代码段。@csaar您可以编写一个代码段吗?因为当我尝试%dd
时,它会出错。或者我不明白,“2m”是什么意思?两个月还是两分钟?2米是一个月,5米是一分钟。编辑,抱歉,没有注意到。另外值得一提的是,OP提供的字符串永远不会工作,因为os.time
需要1970年或更大的年份。此解决方案需要完整的字符串。例如,它不适用于1d
。如果我只给出天、周、年或月,则返回字符串。是的,如果字符串格式正确,这只是一种转换的智能方法。在其他情况下,我需要更多思考^^@jackglowichu您有一些有效字符串输入的示例吗?如果没有,预计会有什么反应?使用Egor Skriptunoff的解决方案
function StrToTime(time_as_string)
local dt = {year = 2000, month = 1, day = 1, hour = 0, min = 0, sec = 0}
local time0 = os.time(dt)
local units = {y="year", m="month", d="day", h="hour", mi="min", s="sec", w="7day"}
for num, unit in time_as_string:gmatch"(%d+)(%a+)" do
local factor, field = units[unit]:match"^(%d*)(%a+)$"
dt[field] = dt[field] + tonumber(num) * (tonumber(factor) or 1)
end
return os.time(dt) - time0
end
print(StrToTime("1d")) -- 86400
print(StrToTime("1d1s")) -- 86401
print(StrToTime("1w1d1s")) -- 691201
print(StrToTime("1w1d")) -- 691200