Compare a range of hours and minutes in JAVA

0

I am implementing a personnel control system, making use of a fingerprint reader.

I am in the validation stage. My question is: How can I validate between the time obtained and the time the user has established in the database, with a range of acceptance minutes?

Until now this is what I have to do the validation.

public void validarHora(ArrayList<Horario> horas) {
    try {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        //obtenemos la hora de chequeo
        String s = df.format(now);
        //Realizamos la validacion
        Date comparar1, comparar2,comparar3;
        //hora actual
        comparar1 = df.parse(s);
        for (Horario hora : horas) {
            //hora1
            comparar2 = df.parse(hora.getHoraEntrada());
            System.err.println(comparar1.compareTo(comparar2));
            //hora2
            comparar3 = df.parse(hora.getHoraSalida());
            System.err.println(comparar1.compareTo(comparar3));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

A simple example that I can give.

I go and check at 6:54 am which is at the time I checked in, and on the BD my check-in time is at 7:00 am with a range of acceptance of 10mins which enters the time within the range and vice versa

    
asked by Miguel Osorio 15.08.2016 в 20:48
source

1 answer

1

The compareTo() method is used to compare objects or in the case of String types to determine the most "large" string; It is not what you need for your particular problem.

To compare 2 dates there are libraries like JodaTime (versions of Java 7 or lower), I understand that Java 8 has a better implementation to work with data types Date .

In particular your case you could work in a simple way and without resorting to external libraries, I propose the following:

public static boolean evaluarLimite(Date date1, Date date2) {
    boolean correcto = false;
    long diferencia = (Math.abs(date1.getTime() - date2.getTime())) / 1000;
    long limit = (60 * 1000) / 1000L;//limite de tiempo

    if (diferencia <= limit) {
        correcto= true;
    }
    return correcto;
}

You indicate that you can base yourself on a time limit (60 seconds in my example) if the time difference between both dates is greater than your limit, then you must make the decision or execute the event that is required.

Adjust the method to measure the unit you want, take into account that what I show you above works based on seconds (millisecs / 1000) = secs.

    
answered by 15.08.2016 / 21:03
source