How to find the difference of two timestamps in java?

94,144

Solution 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();

Solution 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();

Solution 3

You can calculate the difference with the both following methods(also you can modify the mentioned methods to return difference as 'millisecond', 'day', 'month', etc by adding additional if statement or using switch case):

private Long calculateDifference(String date1, String date2, String value) {
        Timestamp date_1 = stringToTimestamp(date1);
        Timestamp date_2 = stringToTimestamp(date2);
        long milliseconds = date_1.getTime() - date_2.getTime();
        if (value.equals("second"))
            return milliseconds / 1000;
        if (value.equals("minute"))
            return milliseconds / 1000 / 60;
        if (value.equals("hours"))
            return milliseconds / 1000 / 3600;
        else
            return new Long(999999999);
    }

private Timestamp stringToTimestamp(String date) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parsedDate = dateFormat.parse(date);
            return new Timestamp(parsedDate.getTime());
        } catch (Exception e) {
            return null;
        }
    }

For example:

calculateDifference("2021-10-20 10:00:01", "2021-10-20 10:15:01", "minute");

will return '-15'

or

calculateDifference("2021-10-20 12:00:01", "2021-10-20 10:15:01", "minute");

will return '105'

Share:
94,144
user2052015
Author by

user2052015

Updated on July 09, 2022

Comments

  • user2052015
    user2052015 almost 2 years

    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!

  • user2052015
    user2052015 over 11 years
    Unfortunately i dont have the objects in my arraylist. There is another class which includes String timeStamp = new SimpleDateFormat("ss S").format(new Date()); and i obtain the timestamps via this part.And i pass the timestamp values to an arraylist of another class and make the calculations by creating a new method.So how could i add this object since because the Date() is in another class???
  • Marc-Emmanuel Ramage
    Marc-Emmanuel Ramage over 11 years
    So, you can't call getTime on a String object because it is not a member of this class. You have to parse the String and format it in a way you can cast it in long.
  • user2052015
    user2052015 over 11 years
    I cannot do this because : 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)
  • user2052015
    user2052015 over 11 years
    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);
  • user2052015
    user2052015 over 11 years
    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 timeStamps to class B. My problem is this substraction 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 ?
  • Marc-Emmanuel Ramage
    Marc-Emmanuel Ramage over 11 years
    You can only call getTime on a Timestamp object or a Date object. If you have a String (the one you pass to the method dialogDuration) you have to parse it back to a Timestamp object or a Date object so you can call getTime on it and get your long value.
  • user2052015
    user2052015 over 11 years
    Thanks a lot Marc but could you please help me with an example because i m kind of novice in java and dont know how to do it exactly???
  • Marc-Emmanuel Ramage
    Marc-Emmanuel Ramage over 11 years
    The code above just do this. It takes a SimpleDateFormat, the same you are using in your class A ("ss S"). You can pass your String to the parse method of the dateFormat object and get a new Date object representing it on which you can call getTime and get your long value.
  • user2052015
    user2052015 over 11 years
    Thank you so much Marc for your help! It works now :) you made my day...Thanks a lot again :)
  • Line
    Line over 5 years
    Hi, your answer is very good and helped me a lot. However, the problem here isn't related to arrays in any way, so I let myself edit it, removing this stuff, which only disturbed me for a while ;) It's about type of the variable - OP operates on Strings, while this answer is for those who operate on Timestamp objects (like me). Doesn't matter if they are in array or separated variables.