问题
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!
回答1:
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();
回答2:
Assuming you have Timestamp objects or Date Objects in your ArrayList you could do:
Timestamp a = timeSt.get(0);
Timestamp b = timeSt.get(timeSt.size()-1);
long diff = b.getTime() - a.getTime();
回答3:
You should make your ArrayList x
to an ArrayList<TimeStamp> x
. Subsequently, your method get(int)
will return an object of type TimeStamp
(instead of a type String
). On a TimeStamp
you are allowed to invoke getTime()
.
By the way, do you really need java.sql.TimeStamp
? Maybe a simple Date
or Calendar
is easier and more appropriate.
来源:https://stackoverflow.com/questions/14810084/how-to-find-the-difference-of-two-timestamps-in-java