将字符串类型时间转换为秒数

我正在尝试设置一个函数,将以下字符串/变量转换为秒数(或Unix时间),但无论我做什么,都卡在了非常复杂的解决方案中。 是否有一种简单的方法可以避免使用多个if语句等?

local test1 = '01h 25m'
local test2 = '05m 24s'
local test3 = '12s'
function transformTime()
  ...
end

现在通过在3个变量上调用此函数,我希望得到: 5100(1 * 60 * 60 + 25 * 60),324(5 * 60 + 24 * 1)和12(12 * 1)。

点赞
用户2858170
用户2858170

你可以简单地使用字符串模式和捕获来获取每个单位的数字。

https://www.lua.org/manual/5.3/manual.html#6.4.1

local test1 = '01h 25m'
local test2 = '05m 24s'
local test3 = '12s'

function transformTime(timeString)
  -- 获取至少1个(+)数字(%d)后跟"s"
  local seconds = timeString:match("(%d+)s") or 0
  seconds = seconds + 60 * (timeString:match("(%d+)m") or 0)
  seconds = seconds + 3600 * (timeString:match("(%d+)h") or 0)

  return seconds

end

print(transformTime(test1))
print(transformTime(test2))
print(transformTime(test3))
2019-10-24 21:48:15