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

15,652

Solution 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

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

Solution 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
$

Solution 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
Share:
15,652
jcrshankar
Author by

jcrshankar

Updated on June 08, 2022

Comments

  • jcrshankar
    jcrshankar almost 2 years

    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?

  • jcrshankar
    jcrshankar about 9 years
    what is this 604800000 am getting results like 823540175
  • Downgoat
    Downgoat about 9 years
    @jcrshankar Oh whoops, a few extra zeros, it should be 604800
  • jcrshankar
    jcrshankar about 9 years
    pday=7 CURRENT=date +"%F %T" --date "$pday days ago" echo $CURRENT how abt this
  • chepner
    chepner about 9 years
    That's fine. The shell handles replacing $pday with 7, so date gets the same argument to --date either way.
  • Thomas Dickey
    Thomas Dickey about 9 years
    Tag says "Unix", but this example does not work with Solaris 10. As a rule, Unix does not allow the date command to be used in this way. Perl can do this, of course.
  • Downgoat
    Downgoat about 9 years
    @ThomasDickey Ah, okay. I don't do much of Unix
  • Thomas Dickey
    Thomas Dickey about 9 years
    Likewise, GNU date is unlikely to be installed on a Unix system (likely only Linux and constructs such as Cygwin).
  • Thomas Dickey
    Thomas Dickey about 9 years
    Interesting (I see it is a relatively new feature -- in the ksh manual on *AST UNIX MANUAL, but not in older versions as seen in *nixDoc. A quick check on a Debian system shows it as part of ksh93 (OP did not provide details).
  • Vinay Prajapati
    Vinay Prajapati almost 6 years
    add some details please and elaborate why your solution works.