Bash: Subtract 10 minutes from a given time

In a bash script, if I have a number representing time in the form of hhmmss (or hmmss), what is the best way to subtract 10 minutes?

those. 90,000 → 85,000

+5
source share
4 answers

This is a bit complicated. Date can do general manipulations, i.e. You can:

date --date '-10 min'

Setting the hour-min-seconds (using UTC, because otherwise it seems to be PM):

date --date '11:45:30 UTC -10 min'

To split the date string, the only way I can think of is to expand the substring:

a=114530
date --date "${a:0:2}:${a:2:2}:${a:4:2} UTC -10 min"

And if you want to just return hhmmss:

date +%H%M%S --date "${a:0:2}:${a:2:2}:${a:4:2} UTC -10 min"
+13
source

why not just use the time of the era, and then take 600 from it?

$ echo "`date +%s` - 600"| bc; date 
1284050588
Thu Sep  9 11:53:08 CDT 2010
$ date -d '1970-01-01 UTC 1284050588 seconds' +"%Y-%m-%d %T %z"
2010-09-09 11:43:08 -0500
+1
source

5 6- , :

$ t=90100
$ while [ ${#t} -lt 6 ]; do t=0$t; done
$ echo $t
090100
$ date +%H%M%S --utc -d"today ${t:0:2}:${t:2:2}:${t:4:2} UTC - 10 minutes"
085100

, --utc UTC , .

For mathematics within bash (i.e., $((and ((), leading zeros will cause the number to be interpreted as octal. However, in any case, your data is more string (with a special format) than numeric. I used the while loop above because it seems like you are treating it as a number and therefore can get 100 in 12:01.

+1
source

My bash version does not support -d or -date as above. However, if you enter the 0-filled input correctly, this works

$ input_time=130503 # meaning "1:05:03 PM"

# next line calculates epoch seconds for today date at stated time
$ epoch_seconds=$(date -jf '%H%M%S' $input_time '+%s')

# the 600 matches the OP "subtract 10 minutes" spec. Note: Still relative to "today"
$ calculated_seconds=$(( epoch_seconds - 600 )) # bc would work here but $((...)) is builtin

# +%H%M%S formats the result same as input, but you can do what you like here
$ echo $(date -r $calculated_seconds '+%H%M%S')

# output is 125503: Note that the hour rolled back as expected.
+1
source

All Articles