Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in time between two dates in java

Tags:

java

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.

like image 324
harishtps Avatar asked May 06 '11 12:05

harishtps


People also ask

How do you calculate duration in Java?

String start = "12:00:00"; String end = "02:05:00"; SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); Date date1 = format. parse(start); Date date2 = format. parse(end); long difference = date2. getTime() - date1.

How can I get the difference between two dates in Java 8?

Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();

How do you subtract time in Java?

minus(long amountTosubtract, TemporalUnit unit) minus() method of a LocalTime class used to returns a copy of this LocalTime with the specified amount of unit subtracted. If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.


1 Answers

   long difference = date2.getTime() - date1.getTime();      // now you have your answer in milliseconds -  //so divide by 1000 to get the time in seconds 
like image 56
planetjones Avatar answered Sep 24 '22 21:09

planetjones