Add 30 days to Date in java

Use a Calendar. http://docs.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html

Pseudo code:

Calendar c= Calendar.getInstance();
c.add(Calendar.DATE, 30);
Date d=c.getTime();

This is because 30 * 1000 * 60 * 60 * 24 overflows Integer.MAX_VALUE, while 20 * 1000 * 60 * 60 * 24 does not.


  1. Date is not tied to any calendar system used by human beings. It just represents point in time. Adding 30 days to Date makes no sense, it is like adding 20 to red color.

  2. Common approach of adding 1000 * 60 * 60 * 24 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 dst. It can be one second longer or shorter due to leap seconds.

  3. What you should do is converting Date into a Calendar (which actually represents some calendar system, like GregorianCalendar. Then simply add days:

    Calendar calendar = new GregorianCalendar(/* remember about timezone! */);
    calendar.setTime(date);
    calendar.add(Calendar.DATE, 30);
    date = calendar.getTime();
    
  4. Use DateUtils.addDays() from Apache Commons Lang:

    DateUtils.add(date, 30);
    

    This does not violate what was written above, it converts to Calendar underneath.

  5. Or avoid this hell altogether and go for Joda Time.

Tags:

Java