Show Difference of 2 instants in SimpleDateFormat format ("yyyy-MM-dd HH: mm: ss.SSS") android

1

I have 2 buttons that get the start, end and duration timestamp of an event, but they look like java.text.SimpleDateFormat@f17b4ca5, but I do not know how to calculate the difference between them.

I would like it to look like this: "2018-04-15-14: 34: 24.567"

MainActivity.java varibles

SimpleDateFormat timestampFin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat timestampInicio = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

public void DefinirHoraInicio(View view)
{
    inicio = timestampInicio.toString();
    Toast.makeText(MainActivity.this, "Inicio del evento: " + inicio, Toast.LENGTH_SHORT).show();
    viewInicio.setText(inicio);

}

public void DefinirHoraFin(View view)
{
    String Duracion = "";
    fin = timestampFin.toString();
    //Duracion = (timestampFin - timestampInicio).toString();
    Duracion = fin;

    Toast.makeText(MainActivity.this, "Fin del evento: " + fin, Toast.LENGTH_SHORT).show();
    viewFin.setText(fin);
    viewDuracion.setText(Duracion);
}
    
asked by Kuroi 15.04.2018 в 21:08
source

1 answer

1

SimpleDateFormat is used to obtain or define the format you want, in this case

"yyyy-MM-dd HH:mm:ss.SSS"

but you are getting values as java.text.SimpleDateFormat@f17b4ca5 , since you are only printing the String representation of the format.

inicio = timestampInicio.toString();
 fin = timestampFin.toString();

To obtain the difference between 2 dates it is necessary to define the initial and the final, as an example:

        String strInicio = "2018-04-18 10:10:09.000";
        String strFin = "2018-04-18 11:10:09.000";

If you want to get these dates in String format, you can use this method:

public static String getDate(long milliSeconds, String dateFormat){
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}

which you can call in this way, defining the format you want to use:

  String strInicio = getDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss.SSS");

From these dates the appropriate format is used and you get the difference you want:

   try {
        Date dInicio = timestampInicio.parse(strInicio);
        Date dFin = timestampFin.parse(strFin);


        long diferencia = (dFin.getTime() - dInicio.getTime()) / 1000;
        Log.i(TAG,"Diferencia : "  + diferencia );

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

In this case the difference is 3600 seconds, which converted to 60 minutes is

    
answered by 16.04.2018 / 19:02
source