简体   繁体   中英

How to calculate date -N in linux shell scripting?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM