Converting string type time to seconds

Viewed 83

I'm trying to setup a function that would transfer below strings / variables into seconds (or unix time), but whatever I do, I stuck in really complicated solutions. Is there a straightforward way to do it without multiple if statements etc?

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

Now by calling this function on 3 variables I would like to get: 5100 (1*60*60+25*60), 324(5*60+24*1) and 12(12*1).

1 Answers

You can simply use string patterns and captures to get the numbers for each unit. 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)
  -- get at least 1(+) digit(%d) followed by "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))
Related