1

I have two hours, in the format (HH: mm) that I have passed to Date to subtract.

By subtracting them, I get the difference in milliseconds, and I convert them to hours dividing by 3600, and to minutes, first dividing by 60, and then doing the% operation.

If, for example, I put the starting time 20:00 and the final time 22:00, I get 0 hours and 2 minutes as a result.

Does anyone see the error?

This is my code:

 hIni.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int hour = calendario.get(Calendar.HOUR_OF_DAY);
                int minute = calendario.get(Calendar.MINUTE);

                final TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                        calendario.set(Calendar.HOUR_OF_DAY, hour);
                        calendario.set(Calendar.MINUTE, minute);

                        horaInicio = String.format("%02d:%02d", hour, minute);
                        hIni.setText(horaInicio);

                        if (!horaFin.equals(""))
                        {
                            if  (testChar(hFin.toString()))
                            {
                                Date hI = ParseHora(horaInicio);
                                Date hF = ParseHora(horaFin);


                                //obtienes la diferencia de las fechas
                                long difference = Math.abs(hF.getTime() - hI.getTime());

                                //obtienes la diferencia en minutos ya que la diferencia anterior esta en milisegundos
                                difference= difference / (60 * 1000);

                                horasDur=difference/60;
                                minDur = difference%60;

                                dur.setText(horasDur +" horas "+minDur+" minutos");

                            }
                        }
                    }
                };
                new TimePickerDialog(NueAvaCuando.this,time, hour, minute, true).show();
            }
        });

        hFin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int hour = calendario.get(Calendar.HOUR_OF_DAY);
                int minute = calendario.get(Calendar.MINUTE);

                final TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                        calendario.set(Calendar.HOUR_OF_DAY, hour);
                        calendario.set(Calendar.MINUTE, minute);
                        horaFin = String.format("%02d:%02d", hour, minute);
                        hFin.setText(horaFin);

                        if (!horaInicio.equals(""))
                        {
                            if  (testChar(hIni.toString()))
                            {
                                Date hI = ParseHora(horaInicio);
                                Date hF = ParseHora(horaFin);

                                //obtienes la diferencia de las fechas
                                long difference = Math.abs(hF.getTime() - hI.getTime());

                                //obtienes la diferencia en horas ya que la diferencia anterior esta en milisegundos
                                difference= difference / (60 * 60 * 1000);

                                horasDur=difference/60;
                                minDur = difference%60;

                                dur.setText(horasDur +"horas "+minDur+" minutos");


                            }
                        }

                    }
                };
                new TimePickerDialog(NueAvaCuando.this,time, hour, minute, true).show();
            }
        });

here the methods:

public static Date ParseHora(String fecha)
    {
        SimpleDateFormat formato = new SimpleDateFormat("HH:mm");
        Date fechaDate = null;
        try {
            fechaDate = formato.parse(fecha);
        }
        catch (ParseException ex)
        {
            System.out.println(ex);
        }
        return fechaDate;
    }


 public boolean testChar(String cadena) {
        if (!Character.isDigit(cadena.charAt(0)))
            return true;
        else
            return false;
    }

thank you very much

midlab
  • 189
  • 1
  • 6
  • Consider using `LocalTime` for your times and `Duration.between()` for finding the difference. The classes and the method mentioned are from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 14 '20 at 14:39
  • Does this answer your question? [Calculate Difference between two times in Android](https://stackoverflow.com/questions/14110621/calculate-difference-between-two-times-in-android). I’m immodest enough to recommend [my own answer](https://stackoverflow.com/a/56413601/5772882) there. You may also search for more. – Ole V.V. Oct 15 '20 at 10:14

1 Answers1

3

The problem is here, inside the onTimeSet method, defined inside the listener passed to hFin.setOnClickListener:

difference= difference / (60 * 60 * 1000);

Before this statement is executed, difference is in milliseconds. The code after this is expecting minutes. However, dividing by 1000 converts milliseconds to seconds, and therefore dividing by 60 * 1000 already gets you to minutes, so dividing by 60 * 60 * 1000 converts to hours, which is not what you want.

That part of the code should be:

difference = difference / (60 * 1000);
Ryan1729
  • 940
  • 7
  • 25