Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

unix

sh

ksh

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?

like image 677
jcrshankar Avatar asked Oct 16 '25 10:10

jcrshankar


2 Answers

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
like image 112
chepner Avatar answered Oct 18 '25 07:10

chepner


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

like image 34
Thomas Dickey Avatar answered Oct 18 '25 09:10

Thomas Dickey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!