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

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...