lua – 如何将字符串时间转换为unix?

我正在创建一个管理工具,我需要将字符串类型转换为:’1y2m3d4h5mi6s’到Lua中的unixtime(秒).我该怎么做?

我希望StrToTime(“1d”)的输出为86400.

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
相关文章
相关标签/搜索
精选24码期期准小鱼儿