繁体   English   中英

我如何在lua中将时间格式化为秒?

[英]How do i format time into seconds in lua?

所以基本上我对如何制作它感到困惑,以便我可以将 DD:HH:MM:SS 转换为只有几秒钟,同时考虑到数字的数量。 (对不起,如果我理解为 0,你肯定知道我在下面的例子中的意思。)

print("05:00":FormatToSeconds()) -- 5 minutes and 0 seconds
-- 300

print("10:30:15":FormatToSeconds()) -- 10 hours, 30 minutes and 15 seconds
-- 37815

print("1:00:00:00":FormatToSeconds()) -- 1 day
-- 86400

print("10:00:00:30":FormatToSeconds()) -- 10 days, 30 seconds
-- 864030

等等等等。 我认为也许使用 gmatch 会起作用,但仍然是 idk。 帮助将不胜感激。

编辑:

因此,我尝试使用 gmatch 进行此操作,但我不知道这是否是最快的方法(可能不是),因此仍将不胜感激。

(我的代码)

function ConvertTimeToSeconds(Time)
    local Thingy = {}
    local TimeInSeconds = 0
    
    for v in string.gmatch(Time, "%d+") do
        if tonumber(string.sub(v, 1, 1)) == 0 then
            table.insert(Thingy, tonumber(string.sub(v, 2, 2)))
        else
            table.insert(Thingy, tonumber(v))
        end
    end
    
    if #Thingy == 1 then
        TimeInSeconds = TimeInSeconds + Thingy[1]
    elseif #Thingy == 2 then
        TimeInSeconds = TimeInSeconds + (Thingy[1] * 60) + Thingy[2]
    elseif #Thingy == 3 then
        TimeInSeconds = TimeInSeconds + (Thingy[1] * 60 * 60) + (Thingy[2] * 60) + Thingy[3]
    elseif #Thingy == 4 then
        TimeInSeconds = TimeInSeconds + (Thingy[1] * 24 * 60 * 60) + (Thingy[2] * 60 * 60) + (Thingy[3] * 60) + Thingy[4]
    end
    
    return TimeInSeconds
end

print(ConvertTimeToSeconds("1:00:00:00"))

在进行任何实际测量之前不要担心执行速度,除非您正在设计一个时间要求严格的程序。 在任何极端情况下,您可能都希望将有风险的部分卸载到 C 模块中。

你的方法很好。 您可以清理某些部分:您可以只返回计算结果,因为TimeInSeconds在您的情况下实际上并不充当累加器; tonumber处理'00'就好了,它可以确保带有参数的十进制整数(从 5.3 开始)。

我会采取另一种方式并在表格中描述因素:

local Factors = {1, 60, 60 * 60, 60 * 60 * 24}
local
function ConvertTimeToSeconds(Time)
  local Components = {}
  for v in string.gmatch(Time, "%d+") do
    table.insert(Components, 1, tonumber(v, 10))
  end
  if #Components > #Factors then
    error("unexpected time component")
  end
  local TimeInSeconds = 0
  for i, v in ipairs(Components) do
    TimeInSeconds = TimeInSeconds + v * Factors[i]
  end
  return TimeInSeconds
end

当然,两种实现都存在模式幼稚的问题,因为它会匹配例如'00 what 10 ever 10' 要解决这个问题,您可以采用另一条路线,使用string.match与例如'(%d+):(%d+):(%d+):(%d+)'并强制执行严格格式,或匹配每个可能的变体。

否则,您可以全力以赴并使用LPeg来解析持续时间。

另一种方法是不在内部使用字符串,而是将它们转换为像{secs=10, mins=1, hours=10, days=1}之类的表,然后改用这些表 - 从该表示中获取秒数将是直接的-向前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM