1

Running into errors. I am trying to get the next month when a user sends a date in.

D="2019/12/01";
D=$(date -d "$D");
echo "Current Date = $D";

prints Current Date = Sun Dec 1 00:00:00 EST 2019

current_month=$(date -d "$D" '+%m');
echo "Current Month = $current_month";

prints Current Month = 12

nextm=$(date -d "$D" "+next months");
echo "Next Month = $nextm";

prints Next Month = next months How do I get the next month?

**************** update ************************

D="2019/11/01";
D=$(date -d "$D");
echo "Current Date = $D";
Current Date = Fri Nov  1 00:00:00 EDT 2019
current_month=$(date -d "$D" '+%m');
echo "Current Month = $current_month";
Current Month = 11

next_date=$(date -d "$D next month")
echo "Next Date = $next_date";
Next Date = Sat Nov 30 23:00:00 EST 2019
next_year=$(date -d "$next_date" '+%Y');
echo "Next Year = $next_year";
Next Year = 2019

printing out november 30 instead of december 1

1
  • Seems to be an issue with daylight savings. I think you may only be able to avoid this by using UTC or forcing the same UTC offset like TZ='UTC-4:00' date -d "$D next month"
    – jesse_b
    Commented May 9, 2019 at 17:12

1 Answer 1

3

You can add one month to your input date string (using GNU date) like so:

nextm=$(date -d "$D +1 month")

Or:

nextm=$(date -d "$D next month")

When you quote $D and +next months separately that becomes two different parameters which will not be read by date in the way you want it to be.

3
  • Thanks. Is what I have the best way to get the next month. When I changed the date to 2019/11/01 then the next month is Sat Nov 30 23:00:00 EST 2019 which is incorrect. Commented May 9, 2019 at 16:45
  • 1
    @user3525290: I cannot reproduce that issue, what version of date are you using and what is the exact command that produces that?
    – jesse_b
    Commented May 9, 2019 at 16:48
  • date (GNU coreutils) 8.25. I will edit my original post to exactly what I have. Commented May 9, 2019 at 16:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.