Loop in time interval

Asked

Viewed 307 times

0

I need to go through an hour interval to assemble a grid with schedules. Example: range 08:00 to 10:00, adding 30 minutes. Forming a grid like this: 08:00 08:30 09:00 09:30 10:00

I’m trying like this:

    GregorianCalendar gc = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    Date hInicial = null, hFinal = null;

    try {
        hInicial = sdf.parse("08:00");
        hFinal = sdf.parse("10:00");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    GregorianCalendar inicio = new GregorianCalendar();
    inicio.setTime(hInicial);
    GregorianCalendar fim = new GregorianCalendar();
    fim.setTime(hFinal);

    gc.setTime(hInicial);
    while(!inicio.after(fim)) {

        gc.add(Calendar.MINUTE, 30);

    }

The system loops infinitely.

Thank you in advance.

2 answers

0


The problem is that you are testing whether the variable inicio is after fim and within the while you do not modify either of the two variables. Try using inicio instead of gc. Thus remaining:

while(!inicio.after(fim)) {

    inicio.add(Calendar.MINUTE, 30);

}

0

You never change the state of inicio nor fim in the body of his while, then the value of inicio.after(fim) will never change, causing the endless loop.

Browser other questions tagged

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