title: Difference in days between two dates in Java?
body: <p>I need to find the <strong>number of days between two dates</strong>: one is from a report and one is the current date. My snippet:</p>
  
  <pre><code>  int age=calculateDifference(agingDate, today);
  </code></pre>
  
  <p>Here <code>calculateDifference</code> is a private method, <code>agingDate</code> and <code>today</code> are <code>Date</code> objects, just for your clarification. I've followed two articles from a Java forum, <a href="http://forums.sun.com/thread.jspa?messageID=1714945#1714945" rel="nofollow noreferrer">Thread 1</a> / <a href="http://forums.sun.com/thread.jspa?messageID=2292039#2292039" rel="nofollow noreferrer">Thread 2</a>. </p>
  
  <p>It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values. </p>
  
  <p>Why is it happening and how can I fix it?</p>
  
  <p><strong>EDIT :</strong></p>
  
  <p>I'm getting a greater number of days compared to the actual amount of Days.</p>
  
  <pre><code>public static int calculateDifference(Date a, Date b)
  {
      int tempDifference = 0;
      int difference = 0;
      Calendar earlier = Calendar.getInstance();
      Calendar later = Calendar.getInstance();
  
      if (a.compareTo(b) &lt; 0)
      {
          earlier.setTime(a);
          later.setTime(b);
      }
      else
      {
          earlier.setTime(b);
          later.setTime(a);
      }
  
      while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
      {
          tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
          difference += tempDifference;
  
          earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
      }
  
      if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
      {
          tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
          difference += tempDifference;
  
          earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
      }
  
      return difference;
  }
  </code></pre>
  
  <p><strong>Note :</strong></p>
  
  <p>Unfortunately, none of the answers helped me solve the problem. I've accomplished <a href="https://stackoverflow.com/questions/3329469/difference-in-days-between-two-java-dates">this problem</a> with the help of <a href="http://sourceforge.net/projects/joda-time/files/joda-time/" rel="nofollow noreferrer">Joda-time</a> library.</p>