Help with Java code date date

0

Could you help me please, I have a date eg: Year / month / day 2018/05/05 I need that when I add a button this one adds me a month 2018/06/05 but the day remains the same, I have to put the variable in Date because I'm thinking of taking it to my database phpMyAdmin, Basically that when they undad the button to pay the variable in which I have the date of the last payment, change and move on to the next month

    
asked by Alejandro Mejia 25.05.2018 в 00:21
source

2 answers

1

As you mentioned @E. Betanzos, you should use Calendar:

String fechaInicial = "2018/05/05";

SimpleDateFormat formateador = new SimpleDateFormat("yyyy/MM/dd");
Date fecha = parser.parse(fechaInicial);

Calendar calendario = Calendar.getInstance();
calendario.setTime(fecha);
calendario.add(Calendar.MONTH, 1);

String fechaConUnMes = formateador.format(calendario.getTime());
System.out.println("Ahora " + fechaConUnMes);

I have not tested it, but it should work.

    
answered by 25.05.2018 в 01:21
0

I do not recommend the Calendar API at all. JodaTime is a much better implementation, with a much more elegant design. You have very useful methods to work with dates, including plusMonths that what you do, as you can see by name, is adding n months to your date object. I show you examples:

The first is the case that you raise, I have 2018/05/05 and I must obtain 2018/06/05. In the second case I have 2016/01/29 (leap year) and I must get 2016/02/29

    public class FechasTest {

        private DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd");

        @Test
        public void debeAumentarUnMesALaFecha() {

            LocalDate fecha = formatter.parseDateTime("2018/05/05").toLocalDate();
            LocalDate fechaEsperada = formatter.parseDateTime("2018/06/05").toLocalDate();

            assertThat(fecha.plusMonths(1)).isEqualTo(fechaEsperada);
        }

        @Test
        public void obtengo29DeFebreroPorqueEsUnAnioBisiesto() {

            LocalDate fecha = formatter.parseDateTime("2016/01/29").toLocalDate();
            LocalDate fechaEsperada = formatter.parseDateTime("2016/02/29").toLocalDate();

            assertThat(fecha.plusMonths(1)).isEqualTo(fechaEsperada);
        }
    }
    
answered by 25.05.2018 в 05:01