subtract 1 hour from date in unix shell script

2019-03-22 14:09发布

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"`

7条回答
地球回转人心会变
2楼-- · 2019-03-22 14:27

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. Best Regards!

查看更多
做个烂人
3楼-- · 2019-03-22 14:29

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

查看更多
女痞
4楼-- · 2019-03-22 14:37

if you need substract with timestamp :

timestamp=$(date +%s -d '1 hour ago');
查看更多
老娘就宠你
5楼-- · 2019-03-22 14:38
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
查看更多
混吃等死
6楼-- · 2019-03-22 14:39

The following command works on recent versions of GNU date:

date -d '1 hour ago' "+%m/%d/%Y -%H:%M:%S"
查看更多
干净又极端
7楼-- · 2019-03-22 14:43

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

查看更多
登录 后发表回答