Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment Date String by 1 Day

Tags:

java

I have a date String newDate = "31.05.2001"

which I have to increment by 1 day.

I tried the following code:

String dateToIncr = "31.12.2001";
String dt="";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy"); 
Calendar c = Calendar.getInstance();
try {
    c.setTime(sdf.parse(dateToIncr));
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 
c.add(Calendar.DAY_OF_MONTH, 1);  // number of days to add
dt = sdf.format(c.getTime());
System.out.println("final date now : " + dt);

But with this code, it is only managing to add the DAY i.e output of 31.05.2001 will be 1.05.2001 keeping the month and the year unchanged! Please help me with this.

I've also tried

c.roll(Calendar.DATE, 1);  // number of days to add
like image 953
Alpesh003 Avatar asked Jul 13 '11 06:07

Alpesh003


1 Answers

You should use new SimpleDateFormat("dd.MM.yyyy");

'mm' means minutes, 'MM' is months.

like image 158
Fortega Avatar answered Sep 30 '22 08:09

Fortega