如何在java中找到两个时间戳的区别?

use*_*015 9 java datetime arraylist date-difference

我有一个ArrayList包括几个时间戳的目标是找到第一个和最后一个元素的差异ArrayList.

String a = ArrayList.get(0);
String b = ArrayList.get(ArrayList.size()-1);
long diff = b.getTime() - a.getTime();
Run Code Online (Sandbox Code Playgroud)

我也将类型转换为int但仍然给我一个错误The method getTime is undefined for the type String.

附加信息 :

我有一个A类,其中包括

String timeStamp = new SimpleDateFormat("ss S").format(new Date());
Run Code Online (Sandbox Code Playgroud)

并且有一个B类有一个方法 private void dialogDuration(String timeStamp)

dialogueDuration方法包括:

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); 
Run Code Online (Sandbox Code Playgroud)

一个条件是语句(String timeStamp = new SimpleDateFormat("ss S").format(new Date());)不会在类A中更改.并且类A的对象在类A中创建,以便它调用dialogueDuration(timeStamp)方法并将时间戳的值传递给类B.

我的问题是这个减法不起作用,它给出了一个错误cannot invoke getTime() method on the primitive type long.它也为int和String类型提供了同样的错误?

非常感谢提前!

小智 12

也许是这样的:

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


小智 5

假设您的 ArrayList 中有 Timestamp 对象或 Date 对象,您可以执行以下操作:

Timestamp a = timeSt.get(0);

Timestamp b = timeSt.get(timeSt.size()-1);

long diff = b.getTime() - a.getTime();
Run Code Online (Sandbox Code Playgroud)