-1

I need to increment date by some days.

private Date now = new Date();
private Date result;

public void incrementDate(Integer days) {

    result = 

}

So if days equals 3 i need to increment my now date on 3 days and set it to result.

I know that java 8 has plusDays method in LocalDate class. Is there a way how to implement this in java 7.

user3673623
  • 1,795
  • 2
  • 12
  • 18

4 Answers4

0

Use Calendar

Calendar cal = Calendar.getInstance ();
cal.setTime (now);

cal.add (Calendar.DATE, days);

plus other fun stuff.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Use Calendar to do this:

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE,3);
result = cal.getTime()
Jens
  • 67,715
  • 15
  • 98
  • 113
0

I suggest you make the function static and pass in now. return Date and use a Calendar. Something like,

public static Date incrementDate(Date now, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(now);
    cal.add(Calendar.DAY_OF_MONTH, days);
    return cal.getTime();
}

And then to test it

public static void main(String[] args) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date now = new Date();
    System.out.println(df.format(now));
    System.out.println(df.format(incrementDate(now, 3)));
}

Output here (today) is

2014-11-12
2014-11-15
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

try this code :

SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
Date now = new Date();
suresh manda
  • 659
  • 1
  • 8
  • 25