Generating dates, from a typed date and month quantity informed

0

I have to generate an automatic date from the date and amount of month reported.

      Ex:Data digitada: 01/04/2014, Quantidade mês: 5 meses.

Every time the year is out, it switches to the next auto.

    
asked by anonymous 01.12.2014 / 13:54

2 answers

0

The OP found a solution by itself.

Even so, by reference, here's how I would do it in Java 8 with Date and Time API :

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

// ...

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String comecoCurso = "19/11/2014";
int duracaoCurso = 5;
//  Na vida real faca algo com excecoes como DateTimeParseException e DateTimeException
LocalDate terminoCurso = LocalDate.parse(comecoCurso, formatter).plusMonths(duracaoCurso);
System.out.print(terminoCurso.format(formatter));

And the version for Java 7 or lower:

import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat; 

// ...

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String comecoCurso = "19/11/2014";
int duracaoCurso = 5;
try {
    Date dataInicial = formatter.parse(comecoCurso);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dataInicial);
    calendar.add(Calendar.MONTH, duracaoCurso);
    Date dataTermino = calendar.getTime();
    System.out.println(formatter.format(dataTermino));
} catch (ParseException e) {
    // trate essa e outras excecoes
}
    
01.12.2014 / 15:57
0

[RESOLVED THIS FORM]

    String data_f = "";
    GregorianCalendar gc = new GregorianCalendar();
    String data = "19/11/2014";
    Integer duracaoCurso = 5;

    Integer ano = Integer.valueOf(data.substring(6, 10));



    Date datadig = formatarData(data);

    for (int i = 0; i < duracaoCurso; i++) {
        gc.setTime(datadig);
        gc.add(Calendar.MONTH, duracaoCurso);

        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        java.util.Date d = (java.util.Date) gc.getTime();

        if (ano == gc.get(Calendar.YEAR)) {

            gc.set(GregorianCalendar.YEAR, gc.get(Calendar.YEAR) + 1);
        } else {
            gc.set(GregorianCalendar.YEAR, gc.get(Calendar.YEAR));
        }


        if (i == duracaoCurso - 1) {
            data_f = df.format(d);

        }

    }

    System.out.println(data_f);
}

private static Date formatarData(String data) throws ParseException, Exception {
    String temp = data;
    temp = temp.replace("/", "").trim();
    if (temp == null || temp.trim().isEmpty()) {
        throw new Exception("Data  em branco - Por favor verifique a data digitada!");
    } else {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        return new Date(formatter.parse(data).getTime());
    }
}

Exit 19/04/2015, added 5 months ago to date;

    
01.12.2014 / 15:02