操作系统:Red Hat Enterprise Linux Server 7.2(Maipo)
我想把时间缩短到最接近的5分钟,只是向上,而不是向下,例如:
08:09:15应该是08:10:00
08:11:26应该是08:15:00
08:17:58应该是08:20:00
我一直在尝试:
(date -d @$(( (($(date +%s) + 150) / 300) * 300)) "+%H:%M:%S")
这将会延长时间但也会下降(08:11:18将导致08:10:00而不是08:15:00)
知道我怎么能做到这一点?
您可以使用此实用程序功能进行四舍五入:
roundDt() {
local n=300
local str="$1"
date -d @$(( ($(date -d "$str" '+%s') + $n)/$n * $n)) '+%H:%M:%S'
}
然后调用此函数:
roundDt '08:09:15'
08:10:00
roundDt '08:11:26'
08:15:00
roundDt '08:17:58'
08:20:00
要跟踪此函数的计算方式,请在导出后使用-x
(跟踪模式):
export -f roundDt
bash -cx "roundDt '08:11:26'"
+ roundDt 08:11:26
+ typeset n=300
+ typeset str=08:11:26
++ date -d 08:11:26 +%s
+ date -d @1535631300 +%H:%M:%S
08:15:00
GNU日期已经可以计算了。它在“Relative items in date strings”一章的手册中有解释。所以你只需要一个date
电话。
d=$(date +%T) # get the current time
IFS=: read h m s <<< "$d" # parse it in hours, minutes and seconds
inc=$(( 300 - (m * 60 + s) % 300 )) # calculate the seconds to increment
date -d "$d $inc sec" +%T # output the new time with the offset
顺便说一句:+%T
is the same as +%H:%M:%S
。