Subtract 1 hour from date in UNIX shell script Subtract 1 hour from date in UNIX shell script shell shell

Subtract 1 hour from date in UNIX shell script


The following command works on recent versions of GNU date:

date -d '1 hour ago' "+%m/%d/%Y -%H:%M:%S"


date -v-60M "+%m/%d/%Y -%H:%M:%S"DATE=`date -v-60M "+%m/%d/%Y -%H:%M:%S"`

If you have bash version 4.4+ you can use bash's internal date printing and arithmetics:

printf "current date: %(%m/%d/%Y -%H:%M:%S)T\n"printf "date - 60min: %(%m/%d/%Y -%H:%M:%S)T\n" $(( $(printf "%(%s)T") - 60 * 60 ))

The $(printf "%(%s)T") prints the epoch seconds, the $(( epoch - 60*60 )) is bash-aritmetics - subtracting 1hour in seconds. Prints:

current date: 04/20/2017 -18:14:31date - 60min: 04/20/2017 -17:14:31


if you need substract with timestamp :

timestamp=$(date +%s -d '1 hour ago');