简体   繁体   中英

Incrementing user time variable Bash

In the script I'm working on the user defines a variable labeled start time. I would like to increment and decrement that variable by ±3 hrs. The format is 00:00:00 (24hr) and I'm uncertain if there is a better way that doesn't involve string manipulation because if it is less than zero I can't pass -03:00:00 to the Python script that utilizes this variable.

#somescript.sh 00:01:35    
STARTTIME=$1
E=${STARTTIME%*:}
S=${STARTTIME##*:} && ((S=S+3)
echo "$S : $E"

Desired Result: 03:01:35 and 21:01:35

Reviewed: String Operators and Incrementing time (minutes and seconds) in bash / shell script prior to asking this question. Any assistance would be appreciated.

starttime=$1
endtime=$(date -u -d "$starttime 3 hours" +'%H:%M:%S')
echo "${starttime} - $endtime"

...used as:

$ ./add-time 01:01:35
01:01:35 - 04:01:35

If you need to go in the opposite direction, add the word "ago":

endtime=$(date -u -d "$starttime 3 hours ago" +'%H:%M:%S')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM