【发布时间】:2017-07-28 23:37:48
【问题描述】:
我需要一个 Lua 4 脚本,它将自 seconds = 0 以来经过的秒数转换为 D:HH:MM:SS 格式的字符串。我看过的方法尝试将数字转换为日历日期和时间,但我只需要自0 以来经过的时间。如果日值增加到数百或数千,这没关系。怎么写这样的脚本?
【问题讨论】:
我需要一个 Lua 4 脚本,它将自 seconds = 0 以来经过的秒数转换为 D:HH:MM:SS 格式的字符串。我看过的方法尝试将数字转换为日历日期和时间,但我只需要自0 以来经过的时间。如果日值增加到数百或数千,这没关系。怎么写这样的脚本?
【问题讨论】:
这类似于其他答案,但更短。返回行使用格式字符串 in 以 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
【讨论】:
format 功能。但无论如何我都会标记这个答案,因为我认为它是最好的。
试试这个:
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))
【讨论】:
tostring(hours) 应替换为 string.sub(100+hours, -2) 或 ("0"..hours):sub(-2) 以生成 2 位字符串(“HH”格式)。
strsub(100+hours, -2)
math.floor 对于 Lua 4 应该替换为 floor
我找到了一个我能够适应的 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
【讨论】: