Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I incement date by 6 months in Java [duplicate]

I want to increment months by 6 in Java, currently I am using below code. But it is always printing first month. Can you kindly let me know what I am doing mistake here? I am beginner in Java.

This is my output :

Current date : 11-1-2013

date after 6 months : 11-7-2013

Expected output:

Current date: 11-05-2013

date after 6 months : 11-11-2013

        String dt = "11-05-2013";
        DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy"); 
        Date date = null;
        try {
            date = (Date)formatter.parse(dt);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        Calendar now = Calendar.getInstance();    
        now.setTime(date);



        System.out.println("Current date : " + now.get(Calendar.DATE)+ "-" +(now.get(Calendar.MONTH) + 1) + "-"
             + now.get(Calendar.YEAR));

        now.add(Calendar.MONTH, 6);

        System.out.println("date after 6 months : " +  now.get(Calendar.DATE)+"-" + (now.get(Calendar.MONTH) + 1) + "-"
             + now.get(Calendar.YEAR));
like image 678
Ranveer Singh Rajpurohit Avatar asked Sep 15 '25 12:09

Ranveer Singh Rajpurohit


1 Answers

Try with capital M:

DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
like image 109
Alex Avatar answered Sep 18 '25 02:09

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!