Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 30 days to Date in java

Tags:

java

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 
like image 678
Elye M. Avatar asked Jul 30 '12 19:07

Elye M.


People also ask

How do I add 7 days to Java Util date?

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.

How do you add and subtract dates in Java?

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.


2 Answers

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(); 
like image 111
Olivier Refalo Avatar answered Sep 23 '22 14:09

Olivier Refalo


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

like image 41
Stefan Mücke Avatar answered Sep 20 '22 14:09

Stefan Mücke