Calculate the 5 minutes ceiling

Viewed 115

Operating System: Red Hat Enterprise Linux Server 7.2 (Maipo)

I want to round the time to the nearest 5 minutes, only up, not down, for example:

08:09:15 should be 08:10:00

08:11:26 should be 08:15:00

08:17:58 should be 08:20:00

I have been trying with:

(date -d @$(( (($(date +%s) + 150) / 300) * 300)) "+%H:%M:%S")

This will round the time but also down (08:11:18 will result in 08:10:00 and not 08:15:00)

Any idea how i can achieve this?

2 Answers

You may use this utility function for your rounding up:

roundDt() {
   local n=300
   local str="$1"
   date -d @$(( ($(date -d "$str" '+%s') + $n)/$n * $n)) '+%H:%M:%S'
}

Then invoke this function as:

roundDt '08:09:15'
08:10:00    

roundDt '08:11:26'
08:15:00

roundDt '08:17:58'
08:20:00

To trace how this function is computing use -x (trace mode) after exporting:

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 date can calculate already. It is explained in the manual in the chapter "Relative items in date strings". So you need just one date call.

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

Btw: +%T is the same as +%H:%M:%S.

Related