0

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.

Community
  • 1
  • 1
ImNotLeet
  • 381
  • 5
  • 19
  • 1
    The second question you supposedly reviewed has answers showing how to use GNU date to do date math, which is the appropriate tool for the job. – Charles Duffy Jun 02 '15 at 00:14
  • @CharlesDuffy I wouldn't have linked it if I didn't review it. There is a date component elsewhere in the script that is not included in the question that I was concerned would cause a issue with my date. Thank you for your assistance. – ImNotLeet Jun 02 '15 at 00:23
  • BTW, all-caps names are reserved for shell builtin variables and environment variables. See the fourth paragraph of http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html, keeping in mind that environment variables and shell variables share a namespace. – Charles Duffy Jun 02 '15 at 00:24
  • I'm hard-pressed to see how code elsewhere in your script could interfere with `date -d`, unless you're modifying environment variables associated with timezones. Anyhow, if there's a restriction that impacts the range of possible answers, include it! – Charles Duffy Jun 02 '15 at 00:24
  • Thanks for the further clarification @CharlesDuffy, I wasn't aware thus the question. Still learning; really appreciate it! – ImNotLeet Jun 02 '15 at 00:26

1 Answers1

2
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')
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441