How to make the difference in hours of two dates in android

0

Hello, what happens is that I need to make the difference between two data, for example:

String fecha_entra ="2018/09/13 10:14:00"

String fecha_sale ="2018/09/14 01:10:20"

and in a third variable the result in hours. I know that these data go with formats but I have not been able to find the correct code, I thank you in advance for your collaboration.

    
asked by juan perez 14.09.2018 в 21:31
source

1 answer

0

Good morning Juan I share a way in which you can get the difference in hours:

try {
    //Lo primero que tienes que hacer es establecer el formato que tiene tu fecha para que puedas obtener un objeto de tipo Date el cual es el que se utiliza para obtener la diferencia.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", Locale.getDefault());

    //Parceas tus fechas en string a variables de tipo date se agrega un try catch porque si el formato declarado anteriormente no es igual a tu fecha obtendrás una excepción
    Date dateStart = dateFormat.parse("2018/09/13 10:14:00");
    Date dateEnd = dateFormat.parse("2018/09/14 01:10:20");

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

    //obtienes la diferencia en horas ya que la diferencia anterior esta en milisegundos
    difference= difference / (60 * 60 * 1000);
    Log.e("Difference: " ,  Long.toString(difference));

}catch(Exception e){
    e.printStackTrace();
}

I hope your contribution will be useful.

    
answered by 14.09.2018 в 22:12