Error using local time as a condition

Asked

Viewed 39 times

1

This method I use to validate the entry of a student, and it is not running. The idea is to use local time to validate a student’s entry. If he is from high school, can enter only in the hours between 7 am to 12 pm, if it is elementary II, will join from 13 pm until 18 pm.

public String horario() {
    String d;
    String j;
    Date dataHoraAtual = new Date();
    String hora = new SimpleDateFormat("HH:mm").format(dataHoraAtual);
    j = hora;
    String g = j.substring(0,1);
    int b = Integer.parseInt(g);
    if(b>=7 && b<=12){
        j="ddd";
    }else{
        if(b>=13 && b<=18){
            j = "Fundamental";
        }
    }
    
    return j;
}

Even converting the variable of String for int, the variable j is not being modified and even if I put another variable in its place to return the message, an error occurs in the return.

Even using this line of code:

int b = Integer.parseInt(g.substring(0, 1));

I haven’t found any resolution for this. What returns me is still the local time, as if the variable j had not been modified.

  • 1

    Arthur to get the 2 digits of the hour need to change the substring: j.substring(0,2);

  • 1

    Hello Ricardo, poxaaa, thank you very much!!. Look, I’ll tell you face , something so simple helped a lot. I thank you from my heart and thank you for the attention

  • 1

    In fact you are making an unnecessary turn, turning the date into a string and then converting pieces of the string to number. If you’re using Java >= 8, take a look at the class java.time.LocalTime, and for previous versions, use java.util.Calendar instead of Date - with these classes you can get the numerical values of hour and minute directly (or even compare directly with another date) - look for examples here on the same site that has several

1 answer

0

You are making an unnecessary turn, converting the date to string and then taking pieces of the string and converting to number.

You don’t need any of this, date and time objects already have methods to obtain numerical values and to compare with other dates.

Another detail is that it was not clear what to do with the minutes. For example, the return "ddd" should be when the time is between 7 and 12, but what about the minutes? If it is 12:30, is it "ddd" or not? In short, should it be between 7:00 and 12:00, or between 7:00 and 12:59? The same goes for the "Fundamental", is it until 6:00 or 6:59? From the way you did, I understand it’s probably up to 59 minutes (at least that’s how your logic would work).

Anyway, you can make it simpler. If you’re using Java >= 8, use the API java.time. As you are only interested in the schedule (regardless of the day), you can use a java.time.LocalTime:

public String horario() {
    // horário atual
    LocalTime agora = LocalTime.now();
    // verifica se está entre 07:00 e 12:59
    if (!LocalTime.of(7, 0).isAfter(agora) && agora.isBefore(LocalTime.of(13, 0))) {
        return "ddd";
    }
    // verifica se está entre 13:00 e 18:59
    if (!LocalTime.of(13, 0).isAfter(agora) && agora.isBefore(LocalTime.of(19, 0))) {
        return "Fundamental";
    }
    // se não está em nenhum dos intervalos acima, é inválido
    return "horário inválido";
}

For the opening time, I used ! ... isAfter ("if it is not after"), because the initial time may be earlier than the current time, or equal (if it is exactly 07:00, falls in the "ddd"). As for the final time, I just did agora.isBefore(...) ("Current time is before"). For example, for "ddd", the current time must be before 13:00, which means that if it is up to 12:59:59.999999999 it will be "ddd" (if it is 13:00 no longer enters this if).

Of course it could also be like this:

public String horario() {
    // horário atual
    int hora = LocalTime.now().getHour();
    if (7 <= hora && hora <= 12) {
        return "ddd";
    }
    if (13 <= hora && hora <= 18) {
        return "Fundamental";
    }
    return "horário inválido";
}

But the first option is more flexible, by allowing any combination of hours and minutes. For example, if the departure time is 18:30, it is easier to change the first code by simply changing the LocalTime.of(19, 0) for the value you want. Already using the second code, you would have to get the minutes and put one more condition in the if.


For Java <= 7, one option is to use java.util.Calendar. The difference is that it is a little more annoying to create an instance with a specific time (in the case below, I have created a method for this):

public String horario() {
    // horário atual
    Calendar agora = Calendar.getInstance();
    // verifica se está entre 07:00 e 12:59
    if (criarComHorario(7, 0).compareTo(agora) <= 0 && agora.compareTo(criarComHorario(13, 0)) < 0) {
        return "ddd";
    }
    // verifica se está entre 13:00 e 18:59
    if (criarComHorario(13, 0).compareTo(agora) <= 0 && agora.compareTo(criarComHorario(19, 0)) < 0) {
        return "Fundamental";
    }
    return "horário inválido";
}

private Calendar criarComHorario(int hora, int minuto) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, hora);
    cal.set(Calendar.MINUTE, minuto);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal;
}

Or, if you want the least flexible option, which compares only the time value:

public String horario() {
    // horário atual
    Calendar agora = Calendar.getInstance();
    int hora = agora.get(Calendar.HOUR_OF_DAY);
    if (7 <= hora && hora <= 12) {
        return "ddd";
    }
    if (13 <= hora && hora <= 18) {
        return "Fundamental";
    }
    return "horário inválido";
}

Note: you could even use the getters and setters of Date, but they are deprecated since Java 1.1 so prefer to use Calendar (but only if you are not using Java >= 8, of course, because in this case, prefer to use the java.time).

Browser other questions tagged

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