I have tried to add days to a certain date in such a way that if I have the date 2020-01-22 and I want to add 10 days to it, the result is 2020-02-01 .
I have tried to do it in the following way:
public static String sumarDiasAFecha(String fecha, int dias) {
if(dias == 0){
return fecha;
}
String[] f = fecha.split("-");
Calendar calendar = Calendar.getInstance();
//calendar.setTime(new Date(Integer.parseInt(f[0]), Integer.parseInt(f[1]), Integer.parseInt(f[2])));
calendar.set(Integer.parseInt(f[0]), Integer.parseInt(f[1]), Integer.parseInt(f[2]));
calendar.add(Calendar.DAY_OF_MONTH, dias);
SimpleDateFormat fe = new SimpleDateFormat("YYYY-MM-dd");
return fe.format(calendar.getTime());
}
I have been successful, however I have a small problem because if we do the previous example with the date 2020-01-22 and add 10 days, the result is 2020-03-01 ; that is to say, it adds up the days perfectly, but in turn adds one more month, it does not matter the days of addition, it always adds one more month.
I use the library JDateChooser
to retrieve the base date.
To make an adjustment, remember that you have to subtract -1 from the month entered:
you can see the reason in the source code:
Therefore the first month starts at 0.
This way you will get the desired result:
Example:
Departure:
You must take into account that the months in
Calendar
, go from 0 to 11, that is, month 0 is January, and 11 is December, that is why it increases one month.In the previous line, you are passing the number as it is, without subtracting a unit, so when you pass 2020-01-22 when you get the
1
one that corresponds to the month, you are not referring to January but to February.Should be:
By subtracting a unit in
Integer.parseInt(f[1])-1
, in your case you will be referring to the correct month, which is the format used byCalendar
, as specified in the following link .