Date One Week Ago From Given Date, Not From Current Date

Hi all,

I've used various scripts in the past to work out the date last week from the current date, however I now have a need to work out the date 1 week from a given date.

So for example, if I have a date of the 23rd July 2010, I would like a script that can work out that one week back was the 16th of July 2010.

Can anybody help?

I normally use something like this in perl

use Time::Local;
$back_time = (time() - (1*86400));

Is there a way to replace time() which is the current date with any date I choose?

Thanks in advance!

Try this,

perl -e 'use Time::Local; use POSIX 'strftime';  print strftime "%d/%m/%Y\n", localtime timelocal(0,0,0,23,7-1,2010) - (7*24*60*60);
1 Like

Hi,
another way is to use the fantastic date command, if perl isn't a requirement, and sh is ok.
Example:

date +%Y-%m-%d -d "2008-01-03 -7 days"

or in Your case,

back_time=$(date +%Y-%m-%d -d "2010-07-23 -7 days")

or with variable start date

start_date=2010-07-23
back_time=$(date +%Y-%m-%d -d "$start_date -7 days")

lots of options and very pedagogic!
:wink:

Best regards,
Lakris

Note the the solution by Lakris only works if you are using the GNU date utility.

Hi,

I didn't have GNU date so I used Pravin's perl solution. It works perfectly, many thanks!