Adding days to date

Hi, please can somebody let me know the easiest way to add days to a date.

I can do this in perl but would like to able to do it in a shell script.

Desired output would be:

date +'%Y-%m-%d' + 10 = 2016-05-02

Thank you

Did you consider searching these forums or take a look at the links to (more or less) ready made solutions at the bottom of this page?

Thank you Rudi, yes i was aware of the posts.

Unfortunately i dont have gnu date so cant use date -d. Is the shiftdate script the only way this can be done?

If you know how to do this in perl , aren't you aware that you can invoke perl in a shell script?

Yes,i was just asking if there is an easy shell alternative. Never mind, thanks anyway

You haven't told us what OS you're using and you haven't told us what shell you're using. If you had the GNU date utility, you could use date -d in a shell script (but you have said that is not an option). If you have a recent version of ksh , you could use:

x=10
printf '%(%Y-%m-%d)T\n' "now + $x days"

currently producing the output:

2016-05-02

Of course, it is easy just using a standard date utility, parameter expansions, and arithmetic expansions to get the current date, extract the current day of the month, add the desired number of days you want to go forward and reformat the day of the month in the date output you want as long as the resulting day number is no greater than 28.

Otherwise, if you're unwilling to use perl , you can use date to get the current date and build calendar logic into your shell script, or use date to get the current date and process output from cal to find the date x days later (or earlier).

Hi Don, using AIX 7.1 ksh.

x=10
printf '%(%Y-%m-%d)T\n' "now + $x days"

produces the following:

(%m-0)T

The perl script i use is as below and works fine but i guess im just being curious as to whether there was an easier way in shell without using GNU date or perl

days=7
input_date=2016-04-13
days=$(( (24 * $days) * (60 * 60) ))
echo $days
new_expiry_date=`perl -MTime::Local=timelocal -e '@t = split(/[-\/]/, $ARGV[0]);
 $t[1]--; print timelocal(1,1,1,reverse @t);' $input_date`
new_expiry_date=`perl -MPOSIX=strftime -e 'print strftime("%Y-%m-%d", localtime(
$ARGV[0] + '$days' ));' $new_expiry_date`
echo "new_expiry_date= $new_expiry_date"



#new_expiry_date=$(
#   perl -MTime::Piece -MTime::Seconds -le '
#        $new_expiry_date = Time::Piece->strptime($ARGV[0], "%Y-%m-%d") + '$days
'* ONE_DAY;
 #       print $new_expiry_date->ymd("-")
  #  ' "$input_date"
#)

On AIX 7.1, try that script using ksh93 instead of ksh .

1 Like

Oh wow, that works a treat ! I never even knew about ksh93 before.

Many thanks