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


Write code to add Month to a Date String

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


Use SimpleDateFormat to convert String to Calendar.

Add the Month to the Calendar


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";
    }//from  w w w .  j  a  v a2  s  .co 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.add(Calendar.MONTH, (int) (Math.random() * 5 + 1));
        String newStr = format.format(calendar.getTime());
        return newStr;

Related Exercise