Add method of calendar gives wrong value?

I am trying to change the date on a button click using c.add(Calendar.DATE,1). It should increment the day by 1. The problem is that when the month changes, the date increments to 32 instead of the expected 1 (In January). The month changes to Feb but the date changes to 32 and so on, e.g. 32-Feb-2016.

 final TextView tv_date = (TextView) dialyReportView.findViewById(R.id.datepicker);
 @Override
            public void onClick(View v) {
                Calendar c;
                c= Calendar.getInstance();
                c.add(Calendar.DATE,1);
                SimpleDateFormat df= new SimpleDateFormat("DD-MMM-yyyy");
                String nextDate = df.format(c.getTime());
                tv_date.setText(nextDate);
            }
        });

I am new to programming so any help is appreciated. Thank you! 🙂

Answer

The problem is that you are using D (day of year) instead of d (day of month). For example, the following code outputs 31-Jan-2015 and 32-Feb-2015:

 Calendar c = Calendar.getInstance();
 c.set(2015, 0, 31);
 c.SimpleDateFormat df= new SimpleDateFormat("DD-MMM-yyyy");
 System.out.println(df.format(c.getTime()));
 c.add(Calendar.DATE,1);
 System.out.println(df.format(c.getTime()));

whereas the following outputs 31-Jan-2015 and 01-Feb-2015:

 Calendar c = Calendar.getInstance();
 c.set(2015, 0, 31);
 c.SimpleDateFormat df= new SimpleDateFormat("dd-MMM-yyyy");
 System.out.println(df.format(c.getTime()));
 c.add(Calendar.DATE,1);
 System.out.println(df.format(c.getTime()));

Leave a Reply

Your email address will not be published. Required fields are marked *