title: Difference in time between two dates in java
body: <p>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.</p>
  
  <p>Here's the scenario :</p>
  
  <p>I have a jsp page which set the session every 5 sec </p>
  
  <pre><code>session.setAttribute( "sessionAccessedAt", new Date() );
  </code></pre>
  
  <p>I have a another jsp page which is accessed every 1 sec ,</p>
  
  <pre><code>Date date2 = new Date();
  </code></pre>
  
  <p>Now i have to compare in the another jsp that i have mentioned and invalidate the session,</p>
  
  <pre><code>Date date1 = (Date)session.getAttribute("sessionAccessedAt");
  Date date2 = new Date();
  
  Differnce = date2 - date1;
  </code></pre>
  
  <p>Thereby if the difference exceeds 5 sec, invalidating the session.</p>