Java - Write code to add Month to a Date String in 2018-02-19 format

Requirements

Write code to add Month to a Date String

The date string is in 2018-02-19 format.

Hint

Use SimpleDateFormat to convert String to Calendar.

Add the Month to the Calendar

Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main{
    public static void main(String[] argv){
        String str = "2018-02-19";
        System.out.println(addMonth(str));
    }/* w  w w.j ava2 s.c  o  m*/
    public static String addMonth(String str) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse(str);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, (int) (Math.random() * 5 + 1));
        String newStr = format.format(calendar.getTime());
        return newStr;
    }
}

Related Exercise