Compare hours in Java

3

I am learning Java and I try to make a program that controls the hours of a working day. The idea is: I ask the user for a start time (HH: mm) (of his work for example) and an end time (HH: mm). I keep that in order to be able to work with it later (I do not know how to ask the user for an hour without doing it as a String, since if I do it as a String, I can sneak anything in. It has to do some API to work with hours, that is, compare, add, subtract, ... I have seen the Date and I do not clarify ...

What I need to check is that the end time minus the start time does not exceed 15 hours, that is, your day should not be longer than those 15 hours. (This I do not know how to do ..). Then I need to take blocks or periods between those hours and operate with the hours, separate, group, ... I'm only interested in working with hours and minutes, I do not need the day, month or year. It's for a day's journey. This is what I have for now: Let's see if someone can give me a cable. :)

public static void main(String[] args) throws IOException {
    // TODO code application logic here
    try {
        Scanner in = new Scanner(System.in); // Creamos un objeto de la clase Scanner
        System.out.println("Introduzca la hora de inicio: (hh:mm)");
        LocalTime start = LocalTime.parse(in.next());
        System.out.println("Introduzca la hora de finalización: (hh:mm)");
        LocalTime end = LocalTime.parse(in.next());

        int minutes = (int) ChronoUnit.MINUTES.between(start, end);

        System.out.println("------------------------------");
        if (minutes > (60 * 15)) {//sobrelímite de jornada:
            System.out.println("Límte de jornada!");
            System.out.println("Sobrepasa las 15 horas!!!");
            System.in.read();
        } else {//jornada correcta:
            System.out.println("Límite de 15 horas en la jornada: OK");
            System.out.println("rango de minutos: " + minutes);
            //más cosas..
            //mostramos horas de trabajo total:
            int workhours = minutes / 60;//pasar a horas los minutos trabajados(para mostrarlas)
            if (minutes <= 60 && minutes > 0) {
                System.out.println("Horas de trabajo: " + workhours + " hora.");
                System.out.println("\nPosible trabajo:");
                System.out.println("1 hora de conducción.");
                System.in.read();
            } else {
                if (minutes < 0) {
                    minutes += 60 * 24;
                }
                System.out.println("Horas de trabajo: " + workhours + " horas.");
                //mostramos los periodos:

                if (minutes > 45 && minutes <= 315) {//
                    System.out.println("\nPosible trabajo:");
                    System.out.println("Salida a las " + start + "h,");
                    System.out.println("4:30h de conducción,");
                    System.out.println("1 descanso de 45 min,");
                    System.out.println("fin de trabajo a las " + end + ".");
                    System.in.read();
                }
                if (minutes > 315 && minutes <= 630) {
                    System.out.println("\nPosible trabajo:");
                    System.out.println("Salida a las " + start + "h,");
                    System.out.println("4:30h de conducción,");
                    System.out.println("1 descanso de 45 min,");
                    System.out.println("4:30h de conducción,");
                    System.out.println("1 descanso de 45 min.");
                    System.in.read();
                }
                if (minutes > 630 /*&& minutes<=690*/) {
                    System.out.println("\nPosible trabajo:");
                    System.out.println("Salida a las " + start + "h,");
                    System.out.println("4:30h de conducción,");
                    System.out.println("1 descanso de 45 min,");
                    System.out.println("4:30h de conducción,");
                    System.out.println("1 descanso de 45 min,");
                    System.out.println("60 minutos de conducción.");
                    System.out.println("Alcanzado el límite de 9h de conducción.");
                    System.in.read();
                }
            }
        }
    } catch (DateTimeParseException e) {
        System.out.println("Horas de inicio/fin no válidas!");
        System.in.read();
    }
}
    
asked by Eric Ferrando 11.06.2016 в 20:13
source

3 answers

2
___ erkimt ___ Compare hours in Java ______ qstntxt ___

I am learning Java and I try to make a program that controls the hours of a working day. The idea is: I ask the user for a start time (HH: mm) (of his work for example) and an end time (HH: mm). I keep that in order to be able to work with it later (I do not know how to ask the user for an hour without doing it as a String, since if I do it as a String, I can sneak anything in. It has to do some API to work with hours, that is, compare, add, subtract, ... I have seen the Date and I do not clarify ...

What I need to check is that the end time minus the start time does not exceed 15 hours, that is, your day should not be longer than those 15 hours. (This I do not know how to do ..). Then I need to take blocks or periods between those hours and operate with the hours, separate, group, ... I'm only interested in working with hours and minutes, I do not need the day, month or year. It's for a day's journey. This is what I have for now: Let's see if someone can give me a cable. :)

    LocalTime entrada = null;
    LocalTime salida = null;    

    System.out.print("Hora de ingreso: ");
    String strIngreso = kb.next();
    System.out.print("\nHora de salida: ");
    String strSalida = kb.next();
    try {
       ingreso = LocalTime.parse(strIngreso);
       salida = LocalTime.parse(strSalida);
       // otra lógica
    } catch(DateTimeParseException e) {
       // la hora de entrada o salida es inválida,
       // informar al usuario y volver a pedirla
       pedirHoras();
    }
    
______ ___ azszpr13670

Ask for the time as String and to validate it just try to pause it. For this, use LocalTime keeping hours only (with or without seconds / nano second).

    int minutes = (int) ChronoUnit.MINUTES.between(ingreso, salida);

    if(minutes > (15 * 60)) {
        // alerta, ¡estás explotando a tus empleados!
    }

To check the time between two hours, by ChronoUnit get the difference in minutes between the two times (LocalTime objects) and compare with 60 * 15 that would become the equivalent minutes to 15 hours:

import java.util.*;
import java.time.*;
import java.time.temporal.*;
import java.time.format.*;

public class Demo {

    public static void main(String[] args) {
        try (Scanner kb = new Scanner(System.in)) {
            System.out.print("Ingrese la fecha de ingreso: ");
            LocalTime ingreso = LocalTime.parse(kb.next());
            System.out.print("Ingrese la fecha de salida: ");
            LocalTime salida  = LocalTime.parse(kb.next());

            int minutes = (int) ChronoUnit.MINUTES.between(ingreso, salida);
            if(minutes > (60 * 15)) {
                System.out.println("¡Estás explotando a tus empleados!");
            }
        } catch(DateTimeParseException e) {
            System.out.println("Fecha de ingreso o salida inválida");
        }
    }
}

A more real example:

Ingrese la fecha de ingreso: 08:00
Ingrese la fecha de salida: 23:01
¡Estás explotando a tus empleados!

Exit:

    LocalTime entrada = null;
    LocalTime salida = null;    

    System.out.print("Hora de ingreso: ");
    String strIngreso = kb.next();
    System.out.print("\nHora de salida: ");
    String strSalida = kb.next();
    try {
       ingreso = LocalTime.parse(strIngreso);
       salida = LocalTime.parse(strSalida);
       // otra lógica
    } catch(DateTimeParseException e) {
       // la hora de entrada o salida es inválida,
       // informar al usuario y volver a pedirla
       pedirHoras();
    }
    
______ azszpr13743 ___

First of all, the code that I'm going to pass to you is converting a String text string to Date so I suggest you start to see the use of jcalendar which lets you get the date and time, from that and only I would have to convert the time to string and use the following code that I present to you:

    
______ azszpr13673 ___

It does not make much sense to use a date / time library for something so simple.

To enter the data you have two options:

  • Order hour and minute separately (more recommended in the case of a form)
  • Order hour minute in string separated by ":", separate them with .split ()

In both cases, you convert both fields to %code% (validating), and then you convert everything to minutes and compute the difference. For example:

    int minutes = (int) ChronoUnit.MINUTES.between(ingreso, salida);

    if(minutes > (15 * 60)) {
        // alerta, ¡estás explotando a tus empleados!
    }
    
___
answered by 11.06.2016 в 20:40
0

First of all, the code that I'm going to pass to you is converting a String text string to Date so I suggest you start to see the use of jcalendar which lets you get the date and time, from that and only I would have to convert the time to string and use the following code that I present to you:

    
answered by 13.06.2016 в 08:08
-1

It does not make much sense to use a date / time library for something so simple.

To enter the data you have two options:

  • Order hour and minute separately (more recommended in the case of a form)
  • Order hour minute in string separated by ":", separate them with .split ()

In both cases, you convert both fields to int (validating), and then you convert everything to minutes and compute the difference. For example:

  int hora1,min1,hora2,min2; // ...
  int horamin1 = hora1*60 + min1;
  int horamin2 = hora2*60 + min2;
  int totalminutos = horamin2 - horamin1;
  if(totalminutos < 0 ) totalminutos += 60*24; // intervalo corta medianoche
  boolean masde15horas = totalminutos > 15*60;
    
answered by 11.06.2016 в 21:20