How to find the difference between two timestamps in java?

I have an ArrayList that includes several timestamps, and the goal is to find the difference between the first and last ArrayList elements.

 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 the error The method getTime is undefined for the type String .

Additional Information:

I have a class A that includes

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

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

and dialogueDuration 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 operator ( String timeStamp = new SimpleDateFormat("ss S").format(new Date()); ) will not be changed in class A. And the object of class B is created in class A, so that it calls method dialogueDuration(timeStamp) and passes the values โ€‹โ€‹of timestamps to class B.

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

Thank you very much!

+4
source share
3 answers

Maybe so:

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

Assuming you have Timestamp or Date Objects in your ArrayList, you can do:

 Timestamp a = timeSt.get(0); Timestamp b = timeSt.get(timeSt.size()-1); long diff = b.getTime() - a.getTime(); 
+3
source

You have to make your ArrayList x ArrayList<TimeStamp> x . Subsequently, your get(int) method will return an object of type TimeStamp (instead of type String ). On TimeStamp you are allowed to call getTime() .

By the way, do you really need java.sql.TimeStamp ? Perhaps a simple Date or Calendar simpler and more appropriate.

0
source

All Articles