Java method show dates in a loop

Asked

Viewed 197 times

1

Good evening, I have a method where I receive the amount of installments and start date. I want to add 1 month to this initial date in loop and I’m confused, giving a very different value:

public void faturar(int parcela, String dataFaturamento) {

    try {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date dtFatura = df.parse(dataFaturamento);
        Calendar c = Calendar.getInstance();
        c.setTime(dtFatura);
        for (int i = 0; i < parcela; i++) {
            // Através do Calendar, trabalhamos a data informada e adicionamos 1 mês 
            c.add(Calendar.MONTH +1,i);
            Date dtParcelasGeradas = c.getTime();  
            System.out.println(dtParcelasGeradas );
        }

I wanted my System.out.println to show like this:

19/09/2016 19/10/2016 19/11/2016 19/12/2016 19/01/2017

But the way I’m doing is showing it like this:

Wed Sep 07 00:00:00 BRT 2016   Wed Sep 14 00:00:00 BRT 2016  Wed Sep 28 00:00:00 BRT 2016

1 answer

5


To display in DD/MM/YYYY format it is necessary to use Dateformat. The big problem in your code is only in line c.add(Calendar.MONTH +1,i), the right one is c.add(Calendar.MONTH, 1), because the function expects which attribute will be incremented and the second parameter is the amount that will be increased.

I made it here, and it worked the way you needed it.

public static void faturar(int parcela, String dataFaturamento) {


        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date dtFatura = null;
        try {
            dtFatura = df.parse(dataFaturamento);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(dtFatura);
        for (int i = 0; i < parcela; i++) {
            // Através do Calendar, trabalhamos a data informada e adicionamos 1 mês 
            c.add(Calendar.MONTH, 1);
            Date dtParcelasGeradas = c.getTime();  
            System.out.println(df.format(dtParcelasGeradas ));

        }
    }

inserir a descrição da imagem aqui

  • Thanks, it worked right!!! I did a test with the date being 30/01/2017... the next was 28/02/2017... and all others were 28/03/2017... onwards. There’s no way I’d treat that?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.