Reputation: 1439
I have to find the difference in time between two different date objects in java and if that time exceeds 5 sec i have to invalidate the session.
Here's the scenario :
I have a jsp page which set the session every 5 sec
session.setAttribute( "sessionAccessedAt", new Date() );
I have a another jsp page which is accessed every 1 sec ,
Date date2 = new Date();
Now i have to compare in the another jsp that i have mentioned and invalidate the session,
Date date1 = (Date)session.getAttribute("sessionAccessedAt");
Date date2 = new Date();
Differnce = date2 - date1;
Thereby if the difference exceeds 5 sec, invalidating the session.
Upvotes: 28
Views: 55712
Reputation: 219
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.
Upvotes: 4
Reputation: 13727
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());
Upvotes: 9
Reputation: 691735
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
Upvotes: 9
Reputation: 12633
long difference = date2.getTime() - date1.getTime();
// now you have your answer in milliseconds -
//so divide by 1000 to get the time in seconds
Upvotes: 69