Subtract 1 hour from date in UNIX shell script

Solution 1:

The following command works on recent versions of GNU date:

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

Solution 2:

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:31
date - 60min: 04/20/2017 -17:14:31

Solution 3:

if you need substract with timestamp :

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

Solution 4:

This work on my Ubuntu 16.04 date: date --date="@$(($(date +%s) - 3600))" "+%m/%d/%Y -%H:%M:%S" And the date version is date (GNU coreutils) 8.25