我正在创建一个管理工具,我需要将字符串类型转换为:’1y2m3d4h5mi6s’到Lua中的unixtime(秒).我该怎么做?
我希望StrToTime(“1d”)的输出为86400.
解决方法@H_403_13@
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
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