e-info128
e-info128

Reputation: 4072

best way to handle only hours and minutes in Java

I have an application that manages objects where each object is associated with a class and have the order to execute commands at certain times of day, for example once at 9am, another at 2pm. My question is: what is the best way to handle only times in java? I am using the Calendar and Time classes but I must give obligatorily year, month, day, which for me are unusable data. My account manipulate events schedules through an object that handles dates is not optimal, then as I can do it?

Upvotes: 4

Views: 18946

Answers (5)

naumcho
naumcho

Reputation: 19901

Joda-Time

Use Joda Time, in particular LocalTime.

LocalTime time = new LocalTime(12, 20);

java.time

Similarly, the java.time package built into Java 8 also offers a LocalTime class.

Upvotes: 14

darkled
darkled

Reputation: 257

Best solution for scheduling operations would be cron4j

Upvotes: 0

e-info128
e-info128

Reputation: 4072

very good response naumcho but unfortunately I can not use that version of java. Finally I ended up creating my own class:

public class Tiempo {
    public Integer hora;
    public Integer minuto;
    public Integer segundo;

    public Tiempo(){}

    public Tiempo(String tiempo){
        this.parse(tiempo);
    }

    /**
     * Convierte un tiempo de tipo String a formato Tiempo
     * @param tiempo Tiempo en formato HH:mm:ss (24 horas)
     * @return Retorna true si fué convertido correctamente, en caso contrario retorna false.
     */
    public Boolean parse(String tiempo){
        try{

            this.hora = Integer.parseInt(tiempo.split(":")[0]);
            this.minuto = Integer.parseInt(tiempo.split(":")[1]);
            this.segundo = Integer.parseInt(tiempo.split(":")[2]);

            Boolean valido = (
                (this.hora >= 0) &&
                (this.hora <= 23) &&
                (this.minuto >= 0) &&
                (this.minuto <= 59) &&
                (this.segundo >= 0) &&
                (this.segundo <= 59)
            );

            if(valido){
                return true;

            }else{
                this.hora = null;
                this.minuto = null;
                this.segundo = null;

                return false;
            }


        }catch(Exception e){
            this.hora = null;
            this.minuto = null;
            this.segundo = null;

            return false;
        }
    }

    /**
     *
     * @param a Tiempo a comparar
     * @param b Tiempo a comparar
     * @return Retorna un número negativo si a es menor que b, retorna 0 si son iguales, retorna un número positivo si a es mayor que b, retorna null si uno de ambos tiempos era nulo
     */
    static public Integer comparar(Tiempo a, Tiempo b){

        if((a == null) || (b == null)){
            return null;
        }

        if(a.hora < b.hora) {
            return -1;

        }else if(a.hora == b.hora){

            if(a.minuto < b.minuto){
                return -2;

            }else if(a.minuto == b.minuto){

                if(a.segundo < b.segundo){
                    return -3;

                }else if(a.segundo == b.segundo){

                    return 0;

                }else if(a.segundo > b.segundo){
                    return 3;
                }

            }else if(a.minuto > b.minuto){
                return 2;
            }

        }else if(a.hora > b.hora){
            return 1;
        }

        return null;
    }
}

Use:

Tiempo a = new Tiempo("09:10:05");
Tiempo b = new Tiempo("15:08:31");

if(Tiempo.compare(a, b) < 0){
 // a < b
}

Upvotes: 1

maerics
maerics

Reputation: 156464

Perhaps you could use a custom Comparator which orders Calendar or Time classes only by the fields you desire:

class HourMinuteComparator implements Comparator<Calendar> {
  public int compare(Calendar c1, Calendar c2) {
    int hour1 = c1.get(Calendar.HOUR_OF_DAY);
    int hour2 = c2.get(Calendar.HOUR_OF_DAY);
    if (hour1 == hour2) {
      int minute1 = c1.get(Calendar.MINUTE);
      int minute2 = c2.get(Calendar.MINUTE);
      return minute2 - minute1;
    } else {
      return hour2 - hour1;
    }
  }
}

Upvotes: 0

Getyorma G.
Getyorma G.

Reputation: 1

There's something really powerful out there called Joda Time it provides a quality replacement for the Java date and time classes.

Upvotes: 0

Related Questions