Home > other >  linux date -- increment current date by minutes but prevent overflow (rollover past midnight)
linux date -- increment current date by minutes but prevent overflow (rollover past midnight)

Time:10-07

So I'm trying to get a date, 1 minute into the future, but not allow midnight rollover, e.g.

date -d "23:58:42 300 seconds"  %H:%M:%S

returns "00:03:42", however I want it to be capped at "23:59:59". Any ideas how?

CodePudding user response:

300 seconds is not a minute, but, the easiest way would be a simple script:

#!/bin/bash
t="$1"
interval="$2"

h=$(date -d "$t $interval seconds"  %H)
if [ "$h" = "00" ] ; then
    echo "23:59:59"
else
    date -d "$t $interval seconds"  %H:%M:%S
fi

This works well if your interval is under an hour.

CodePudding user response:

Try it with the following script:

#!/bin/bash

secsToAdd=300
addendTime="23:58:42"

resultTime=$(date -d "$addendTime $secsToAdd seconds"  %H:%M:%S);
midnightTime="23:59:59"

addendTimeSeconds=$(echo "$addendTime" | awk -F: '{ print ($1 * 3600)   ($2 * 60)   $3 }');
midnightTimeSeconds=$(echo "$midnightTime" | awk -F: '{ print ($1 * 3600)   ($2 * 60)   $3 }');

if [[ "$secsToAdd" -gt $((midnightTimeSeconds-addendTimeSeconds)) ]]
then
    echo "$midnightTime"
else 
    echo "$resultTime"
fi

Logic:

If Seconds to add > Midnight time - Addend time -> you have overflow.

(It works regardless of how big the seconds to be added are).

  • Related