Subtract 1 hour from date in UNIX shell script

ShellDatetimeUnix

Shell Problem Overview


I have the following in a shell script. How can I subtract one hour while retaining the formatting?

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

Shell Solutions


Solution 1 - Shell

The following command works on recent versions of GNU date:

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

Solution 2 - Shell

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 - Shell

if you need substract with timestamp :

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

Solution 4 - Shell

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

Solution 5 - Shell

$ date +%Y-%m-%d-%H 
2019-04-09-20

$ date -v-1H +%Y-%m-%d-%H 
2019-04-09-19

But in shell use as like date +%Y-%m-%d-%H, date -v-1H +%Y-%m-%d-%H

Solution 6 - Shell

Convert to timestamp (a long integer), subtract the right number of milliseconds, reformat to the format you need.

Hard to give more details since you don't specify a programming language...

Solution 7 - Shell

If you need change timezone before subtraction with new format too:

$(TZ=US/Eastern date -d '1 hour ago' '+%Y-%m-%d %H:%M')

Solution 8 - Shell

Here another way to subtract 1 hour.

yesterdayDate=`date -d '2018-11-24 00:09 -1 hour' +'%Y-%m-%d %H:%M'` 
echo $yesterdayDate

Output:
2018-11-23 23:09

I hope that it can help someone.

Solution 9 - Shell

DATE=date -1H "+%m/%d/%Y -%H:%M:%S"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionshamir chaikinView Question on Stackoverflow
Solution 1 - ShelldogbaneView Answer on Stackoverflow
Solution 2 - Shelljm666View Answer on Stackoverflow
Solution 3 - ShellleGabianView Answer on Stackoverflow
Solution 4 - Shellray_gView Answer on Stackoverflow
Solution 5 - ShellElangovan PandiyanView Answer on Stackoverflow
Solution 6 - ShellPhiLhoView Answer on Stackoverflow
Solution 7 - ShellKenan DumanView Answer on Stackoverflow
Solution 8 - ShellJavier MuñozView Answer on Stackoverflow
Solution 9 - ShellSkunkView Answer on Stackoverflow