title: Leapday offset - cleaner solution anyone?
body: <p>I needed to define start/end dates for a person's given age.  This seemed simple:</p>
  
  <pre><code>GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(dateOfBirth);
  cal.add(Calendar.YEAR, years);
  Date start = cal.getTime();
  
  cal.add(Calendar.YEAR, 1);    
  cal.add(Calendar.DAY_OF_MONTH, -1);
  Date end = cal.getTime();
  </code></pre>
  
  <p>Ah, but then there are those born on Leap Day Feb 29th.  If the age is not a multiple of 4 then Calendar will round down to the 28th.  In this case, my code above will give a date range ending on Feb 27th, and there'll be a gap.</p>
  
  <p>So, I can easily solve this by checking for this condition, and I can wrap the fix up in some method to avoid duplicating it everywhere.  But I'm wondering, is there a better solution I'm not aware of?  Something that automatically accounts for this special case for a "day before/after" problem?  </p>
  
  <p>Here's my solution:</p>
  
  <pre><code>public static Date getAgeStartEnd(Date d, int age, boolean end) {
      if (d == null) return null;
  
      GregorianCalendar cal = new GregorianCalendar();
      cal.setTime(d);
      int baseDay = cal.get(Calendar.DAY_OF_MONTH);
      cal.add(Calendar.YEAR, age + (end ? 1 : 0));
      int newDay = cal.get(Calendar.DAY_OF_MONTH);
      boolean roundedDown = baseDay != newDay;
  
      if (end &amp;&amp; !roundedDown) 
          cal.add(Calendar.DAY_OF_MONTH, -1);
      else if (!end &amp;&amp; roundedDown)
          cal.add(Calendar.DAY_OF_MONTH, 1);
  
      d = cal.getTime();
      return d;      
  }
  
  Date start = getAgeStartEnd(dateOfBirth, years, false);
  Date end   = getAgeStartEnd(dateOfBirth, years, true);
  </code></pre>