1

I want to know how to calculate date-n where date is systems current date and N is number of days i want to add or subtract.

I am able to do get yesterday's date but dont know how to add or subtract no of days to get desired date :

date_dir=`date +%Y-%m-%d -d yesterday` echo "$date_dir" 

Thanks

2 Answers 2

4

You can supply an argument '-N days' to the -d option:

$ date +%Y-%m-%d -d '-42 days' # This would subtract 42 days from the current date 2013-10-30 $ date +%Y-%m-%d -d '+42 days' # This would add 42 days to the current date 2014-01-22 

and assign the result to a variable:

$ date_dir=$(date +%Y-%m-%d -d '-42 days') $ echo $date_dir 2013-10-30 
Sign up to request clarification or add additional context in comments.

3 Comments

You could also do date +%Y-%m-%d -d '42 days ago'. It's worth nothing that all these examples are with the GNU implementation of date. In BSD and UNIX this typically doesn't work, but sometimes the GNU version is also installed as gdate`.
@janos Thanks for enlightening. Since the question is tagged linux, it seemed safe to assume that GNU date was being used.
Totally, this is just a little extra. I've been very frustrated at some point in my life when I expected my trusty scripts I wrote in Linux to work in Solaris. Since then I know better, and try to be aware of the little differences.
1
var=`date +%s`; date=`date --date=@$var +%Y-%m-%d` echo $date 

you can add/subtract no of days you need. just remember it is in seconds

From man pages:

%s seconds since 1970-01-01 00:00:00 UTC

Convert seconds since the epoch (1970-01-01 UTC) to a date

$ date --date='@2147483647'

edit: devNull provided better answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.