Lua 4 脚本将经过的秒数转换为天、小时、分钟、秒

Lua 4 script to convert seconds elapsed to days, hours, minutes, seconds

我需要一个 Lua 4 脚本,可以将自 seconds = 0 以来经过的秒数转换为 D:HH:MM:SS 格式的字符串。我看过的方法尝试将数字转换为日历日期和时间,但我只需要自 0 以来经过的时间。如果日值增加到数百或数千,那也没关系。我该如何编写这样的脚本?

试试这个:

function disp_time(time)
  local days = floor(time/86400)
  local remaining = time % 86400
  local hours = floor(remaining/3600)
  remaining = remaining % 3600
  local minutes = floor(remaining/60)
  remaining = remaining % 60
  local seconds = remaining
  if (hours < 10) then
    hours = "0" .. tostring(hours)
  end
  if (minutes < 10) then
    minutes = "0" .. tostring(minutes)
  end
  if (seconds < 10) then
    seconds = "0" .. tostring(seconds)
  end
  answer = tostring(days)..':'..hours..':'..minutes..':'..seconds
  return answer
end

cur_time = os.time()
print(disp_time(cur_time))

我找到了一个我能够改编的 Java 示例。

function seconds_to_days_hours_minutes_seconds(total_seconds)
    local time_days     = floor(total_seconds / 86400)
    local time_hours    = floor(mod(total_seconds, 86400) / 3600)
    local time_minutes  = floor(mod(total_seconds, 3600) / 60)
    local time_seconds  = floor(mod(total_seconds, 60))
    if (time_hours < 10) then
        time_hours = "0" .. time_hours
    end
    if (time_minutes < 10) then
        time_minutes = "0" .. time_minutes
    end
    if (time_seconds < 10) then
        time_seconds = "0" .. time_seconds
    end
    return time_days .. ":" .. time_hours .. ":" .. time_minutes .. ":" .. time_seconds
end

这与其他答案类似,但更短。 return 行使用格式字符串以 D:HH:MM:SS 格式显示结果。

function disp_time(time)
  local days = floor(time/86400)
  local hours = floor(mod(time, 86400)/3600)
  local minutes = floor(mod(time,3600)/60)
  local seconds = floor(mod(time,60))
  return format("%d:%02d:%02d:%02d",days,hours,minutes,seconds)
end