【发布时间】:2021-07-15 00:04:09
【问题描述】:
我有一个函数,灵感来自 here 的 hms,但我希望将其扩展为包括处理和显示 Days。
我已经开始编辑脚本,但很快意识到我在处理逻辑方面已经超出了我的能力范围,将数小时变成数天,反之亦然......
这是我目前所拥有的:
#!/bin/bash
rendertimer(){
# convert seconds to Days, Hours, Minutes, Seconds
# thanks to https://www.shellscript.sh/tips/hms/
local seconds D H M S MM D_TAG H_TAG M_TAG S_TAG
seconds=${1:-0}
S=$((seconds%60))
MM=$((seconds/60)) # total number of minutes
M=$((MM%60))
H=$((MM/60))
D=$((H/24))
# set up "x day(s), x hour(s), x minute(s) and x second(s)" format
[ "$D" -eq "1" ] && D_TAG="day" || D_TAG="days"
[ "$H" -eq "1" ] && H_TAG="hour" || H_TAG="hours"
[ "$M" -eq "1" ] && M_TAG="minute" || M_TAG="minutes"
[ "$S" -eq "1" ] && S_TAG="second" || S_TAG="seconds"
# logic for handling display
[ "$D" -gt "0" ] && printf "%d %s " $D "${D_TAG},"
[ "$H" -gt "0" ] && printf "%d %s " $H "${H_TAG},"
[ "$seconds" -ge "60" ] && printf "%d %s " $M "${M_TAG} and"
printf "%d %s\n" $S "${S_TAG}"
}
duration=${1}
howlong="$(rendertimer $duration)"
echo "That took ${howlong} to run."
期望的输出
349261 seconds: “运行时间为 4 天 1 小时 1 分 1 秒。”
127932 seconds: “运行时间为 1 天 11 小时 32 分 12 秒。”
86400 seconds: “这需要 1 天才能运行。”
实际输出
349261 seconds: “运行时间为 4 天 97 小时 1 分 1 秒。”
127932 seconds: “运行时间为 1 天 35 小时 32 分 12 秒。”
86400 seconds: “运行时间为 1 天 24 小时 0 分 0 秒。”
谁能帮我解决这个问题?
【问题讨论】:
标签: bash datetime time timer data-conversion