Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use <a href="http://joda-time.sourceforge.net/" rel="noreferrer">Joda-Time</a>, period! :)</p> <p>Although "greater than 20 years" might be somewhat dependent on which kind of Calendar you're talking about, when you start counting, leap years, or daylight savings, Joda-Time will give you more flexibility that the util.Calendar class. Working with util.Date is not recommended and counting millisecond (or other things like that) will probably lead to buggy code.</p> <p><strong>JODA-TIME Code Samples:</strong></p> <p>Given:</p> <pre><code>int year1 = 2012, month1 = 2, day1 = 7; int year2 = 1987, month2 = 7, day2 = 23; //You can include a TimeZone if needed in the constructors below DateTime dateTime1 = new DateTime(year1, month1, day1, 0, 0); //2012-02-07T00:00:00.000-05:00 DateTime dateTime2 = new DateTime(year2, month2, day2, 0, 0); //1987-07-23T00:00:00.000-04:00 </code></pre> <p>Option 1, boring...</p> <pre><code>DateTime twentyYearsBefore = dateTime1.minusYears(20); //1992-02-07T00:00:00.000-05:00 if(dateTime2.compareTo(twentyYearsBefore) == -1) System.out.println("The difference between the dates is greater than 20 years"); </code></pre> <p>Option 2, good stuff!</p> <pre><code>Days d = Days.daysBetween(dateTime1, dateTime2); int days = d.getDays(); //-8965 days System.out.println("There are " + days + " days between the two dates"); </code></pre> <p>Option 3, rocket science!!! ;)</p> <pre><code>Period periodDifference = new Period(dateTime1, dateTime2); System.out.println(periodDifference); //prints: P-24Y-6M-2W-1D </code></pre> <p>Of course the <a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html" rel="noreferrer">Period</a> class has a ton of methods to get only the relevant fields. Click the following for the APIs of <a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html" rel="noreferrer">DateTime</a> and <a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/Days.html" rel="noreferrer">Days</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload