why when i add 30 days to today's day i got today's day - 30, and when i add 20 it adds??
here is a sample
import java.text.DateFormat; import java.util.Date; public class DatePlus { public static void main(String[] args) { Date now = new Date(); Date now1 = new Date(); Date now2 = new Date(); DateFormat currentDate = DateFormat.getDateInstance(); Date addedDate1 = addDays(now2, 20); Date addedDate2 = addDays(now1, 30); System.out.println(currentDate.format(now)); System.out.println(currentDate.format(addedDate1)); System.out.println(currentDate.format(addedDate2)); } public static Date addDays(Date d, int days) { d.setTime(d.getTime() + days * 1000 * 60 * 60 * 24); return d; } }
"this is the console"
Jul 30, 2012 Aug 19, 2012 Jul 10, 2012
Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.
DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With