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.
Date
is not tied to any calendar system used by human beings. It just represents point in time. Adding 30 days toDate
makes no sense, it is like adding 20 to red color.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.What you should do is converting
Date
into aCalendar
(which actually represents some calendar system, likeGregorianCalendar
. Then simply add days:Calendar calendar = new GregorianCalendar(/* remember about timezone! */); calendar.setTime(date); calendar.add(Calendar.DATE, 30); date = calendar.getTime();
Use
DateUtils.addDays()
from Apache Commons Lang:DateUtils.add(date, 30);
This does not violate what was written above, it converts to
Calendar
underneath.Or avoid this hell altogether and go for Joda Time.