Difference in time between two dates in java

From Java-8 onwards you may use-

ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());

This is a generic Enum using which, it becomes pretty simple to find difference in any Unit.


   long difference = date2.getTime() - date1.getTime();

    // now you have your answer in milliseconds - 
//so divide by 1000 to get the time in seconds

Building on the other answers, java.util.concurrent.TimeUnit makes it very easy to convert between milliseconds, seconds, etc...

 long differenceInSeconds = TimeUnit.MILLISECONDS.toSeconds(date2.getTime() - date1.getTime());

if ((date2.getTime() - date1.getTime()) > 5000) { // getTime returns the time in milliseconds
    // invalidate
}

But the session timeout is supposed to be handled by the container, not by you.

PS : this is easily answered by reading the javadoc : http://download.oracle.com/javase/6/docs/api/index.html

Tags:

Java