Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p><code>Date</code> is not tied to any calendar system used by human beings. It just represents point in time. Adding 30 days to <code>Date</code> makes no sense, it is like adding 20 to <em>red</em> color.</p></li> <li><p>Common approach of adding <code>1000 * 60 * 60 * 24</code> is wrong. You are adding 86400 seconds, but one day is not necessarily 86400 seconds long. It can be one hour longer or shorter due to <a href="/questions/tagged/dst" class="post-tag" title="show questions tagged 'dst'" rel="tag">dst</a>. It can be one second longer or shorter due to <em>leap seconds</em>.</p></li> <li><p>What you <em>should</em> do is converting <code>Date</code> into a <code>Calendar</code> (which actually represents some calendar system, like <code>GregorianCalendar</code>. Then simply add days:</p> <pre><code>Calendar calendar = new GregorianCalendar(/* remember about timezone! */); calendar.setTime(date); calendar.add(Calendar.DATE, 30); date = calendar.getTime(); </code></pre></li> <li><p>Use <a href="http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/time/DateUtils.html#addDays%28java.util.Date,%20int%29"><code>DateUtils.addDays()</code></a> from Apache Commons Lang:</p> <pre><code>DateUtils.add(date, 30); </code></pre> <p>This does not violate what was written above, it converts to <code>Calendar</code> underneath.</p></li> <li><p>Or avoid this hell altogether and go for <a href="http://joda-time.sourceforge.net/">Joda Time</a>.</p></li> </ol>
 

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