Search code examples
linuxbashdateredhat

Calculate the 5 minutes ceiling


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?


Solution

  • 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