How can I find the current date minus seven days in Unix?

人盡茶涼 提交于 2019-12-11 02:41:06

问题


I am trying to find the date that was seven days before today.

 CURRENT_DT=`date +"%F %T"`
 diff=$CURRENT_DT-7 
 echo $diff 

I am trying stuff like the above to find the 7 days less than from current date. Could anyone help me out please?


回答1:


GNU date will to the math for you:

date --date "7 days ago"

Other version will require you to covert the current date into seconds since the UNIX epoch first, manually subtract 7 days' worth of seconds, and convert that back into the desired form. Consult the documentation for your version of date for details on how to convert to and from Unix timestamps. Here's an example using GNU date again:

x=$(date +%s)
x=$((x - 7 * 24 * 60 * 60))
date --date @$x



回答2:


Here is a simple Perl script which (unlike the other examples) works with Unix:

perl -e 'use POSIX qw(ctime); printf "%s", ctime(time - (7 * 24 * 60 * 60));'

(Tested with Solaris 10, and a token Linux system, of course - with the caveat that Perl is not necessarily part of one's configuration, merely very likely).




回答3:


Ksh's printf can do time calculation:

$ printf '%(%Y-%m-%d)T\n'
2015-04-07
$ printf '%(%Y-%m-%d)T\n' '7 days ago'
2015-03-31
$



回答4:


Adding this one for shells on OSX:

date -v-7d
> Tue Apr  3 15:16:31 EDT 2018
date
> Tue Apr 10 15:16:33 EDT 2018

Need that formated?

date -v-7d +%Y-%m-%d
> 2018-04-03



回答5:


I haven't used unix in a while but I found this in one of my scripts

echo `date +%s`-604800 | bc



回答6:


DATE=$(date --date "7 days ago" | awk '{print$1,$2,$3}')
echo "$DATE"
if [ -z "$(grep -i "$DATE" test.log)" ]; then
  exit 1
fi
sed -i "1,/$DATE/d" test.log


来源:https://stackoverflow.com/questions/29475739/how-can-i-find-the-current-date-minus-seven-days-in-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!