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

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

点赞
用户6514903
用户6514903

尝试这个:

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))
2017-07-28 04:55:33
用户330663
用户330663

我找到了一个适合我的 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 // 如果时间小于10,在前面加上“0end
    if (time_minutes < 10) then
        time_minutes = "0" .. time_minutes // 如果时间小于10,在前面加上“0end
    if (time_seconds < 10) then
        time_seconds = "0" .. time_seconds // 如果时间小于10,在前面加上“0end
    return time_days .. ":" .. time_hours .. ":" .. time_minutes .. ":" .. time_seconds // 将转换后的天数、小时数、分钟数、秒数返回
end
2017-07-28 12:33:00
用户7999952
用户7999952

这个代码和其他答案很相似,但是更短。返回的那一行使用了格式化字符串格式将结果以 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
2017-07-28 15:06:18