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