Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add month to a variable date in shell script

Tags:

linux

shell

sh

I have a date being passed into a shell script and have to add a month to that. for eg:

passed_date=2017-06-01

i need to add 1 month to it :

converted_date=2017-07-01

How can i achieve this in a shell script. I tried converting date to seconds since epoch and then adding 1 month like:

date +%s -d 20170601 -d "+1 month"

and then converting seconds back to yyyy-mm-dd by

date -d@$(date +%s -d 20170601 -d "+1 month") +%Y-%m-%d

but its basically adding 1 month to current system date

like image 956
Shanil Avatar asked Dec 13 '22 22:12

Shanil


2 Answers

You seem to be looking for:

date -d "20170601+1 month" +%Y-%m-%d

When using multiple -d flags in the same command, date seems to only use the last one.

And of course, feel free to replace 20170601 by $VAR containing any date.

like image 176
Jedi Avatar answered Jan 01 '23 20:01

Jedi


For macOS High Sierra

date -v+1m -j -f "%Y-%m-%d" "2017-06-01"
like image 45
Anders B Avatar answered Jan 01 '23 19:01

Anders B