0

I'm trying to add days that exceed the month days. example July 1,2019 and I add 32 days so the result would be August 2,2019.

SimpleDateFormat format = new SimpleDateFormat("mm/dd/yyy");
SimpleDateFormat Dateformat = new SimpleDateFormat("mm/dd/yyy");
String getDate = date_pick.getText().toString();
Date mDate;
Date result_desu;
try {
    mDate = format.parse(getDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(mDate);
    calendar.add(Calendar.DATE, 32);
    String formattedDate = Dateformat.format(calendar.getTime());
    date_result.setText(formattedDate);    // format output
} catch (ParseException e) {
    e.printStackTrace();
}

I've been using this code but it turns out the days only reset with the same month example: July 1,2019 ; result: July 2,2019.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
red
  • 25
  • 7
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jul 25 '19 at 07:13
  • 1
    You should be using `LocalDate::plusDays` instead of the terrible legacy date-time classes seen in the Question. – Basil Bourque Jul 25 '19 at 07:32

1 Answers1

0

Try this:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
class Main{
   public static void main(String args[]){
    String oldDate = "2019-07-1";  
    System.out.println("Date before Addition: "+oldDate);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    try{
       c.setTime(sdf.parse(oldDate));
    }catch(ParseException e){
        e.printStackTrace();
     }

    c.add(Calendar.DAY_OF_MONTH, 32);  
    String newDate = sdf.format(c.getTime());  
    System.out.println("Date after Addition: "+newDate);
   }
}

Output:

Date before Addition: 2019-07-1
Date after Addition: 2019-08-02
GOVIND DIXIT
  • 1,748
  • 10
  • 27
  • Happy to help :) – GOVIND DIXIT Jul 25 '19 at 05:44
  • You’d help even more if you (1) explain how your code solves the asker’s problem (2) show a solution using java.time, the modern Java date and time API, or at least mention that `SimpleDateFormat` and `Calendar` are old and poorly designed and that there is a better alternative. – Ole V.V. Jul 25 '19 at 07:28
  • 1
    These terrible date-time classes were supplanted years ago by the modern *java.time* classes defined by JSR 310. – Basil Bourque Jul 25 '19 at 07:28