Search code examples
javadatetimearraylistdate-difference

How to find the difference of two timestamps in java?


I have an ArrayList including several number of time-stamps and the aim is finding the difference of the first and the last elements of the ArrayList.

String a = ArrayList.get(0);
String b = ArrayList.get(ArrayList.size()-1);
long diff = b.getTime() - a.getTime();

I also converted the types to int but still it gives me an error The method getTime is undefined for the type String.

Additional info :

I have a class A which includes

String timeStamp = new SimpleDateFormat("ss S").format(new Date());

and there is a class B which has a method private void dialogDuration(String timeStamp)

and dialogueDuration method includes:

String a = timeSt.get(0); // timeSt  is an ArrayList which includes all the timeStamps
String b = timeSt.get(timeSt.size()-1);   // This method aims finding the difference of the first and the last elements(timestamps) of the ArrayList  (in seconds)

long i = Long.parseLong(a);
long j = Long.parseLong(b);

long diff = j.getTime()- i.getTime();

System.out.println("a: " +i); 
System.out.println("b: " +j); 

And one condition is that the statement(String timeStamp = new SimpleDateFormat("ss S").format(new Date());) wont be changed in class A. And an object of class B is created in class A so that it invokes the dialogueDuration(timeStamp) method and passes the values of time-stamps to class B.

My problem is this subtraction does not work, it gives an error cannot invoke getTime() method on the primitive type long. It gives the same kind of error also for int and String types?

Thanks a lot in advance!


Solution

  • Maybe like this:

    SimpleDateFormat dateFormat = new SimpleDateFormat("ss S");
    Date firstParsedDate = dateFormat.parse(a);
    Date secondParsedDate = dateFormat.parse(b);
    long diff = secondParsedDate.getTime() - firstParsedDate.getTime();