-1

I want to increment the date by one. I have the below code while running the code I am getting unparseable date finally I want the date as string in the format of MM-DD-YYYY. But same program is working with the YYYY-MM-DD format but i want mydate in this format(MM-DD-YYYY)

String dt = schReq.getStartDate();  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, days);  // number of days to add
dt = sdf.format(c.getTime()); 
schReq.setStartDate(dt);

Can anyone please help me?

Tabrej Khan
  • 894
  • 6
  • 15
Narendra
  • 127
  • 3
  • 11

2 Answers2

1

You have to use two different DateFormats:

one for parsing the string and one for formatting.

String dt = schReq.getStartDate();  // Start date
SimpleDateFormat sdf_parser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf_parser.parse(dt));
c.add(Calendar.DATE, days);  // number of days to add
dt = sdf.format(c.getTime()); 
schReq.setStartDate(dt);
Jens
  • 67,715
  • 15
  • 98
  • 113
  • Thank you Jens for your reply.if i executed the above code in the place of dt i given dt="12-17-2014" i am getting 07-07-0017 as output but i need to get 12-18-2014 – Narendra Dec 17 '14 at 08:06
  • @user3669480 Sorry my fauld. I have updated my answer. Please try again – Jens Dec 17 '14 at 08:07
  • again same problem now it is showing 11-05-0018 as a date – Narendra Dec 17 '14 at 08:20
  • In your question you say the dt has the format `YYYY-MM-DD` and now you give the format `MM-dd-yyyy`. Here is something worng. – Jens Dec 17 '14 at 08:27
1

The code should be working fine as long as dt and days are correct. This gave me 12-18-2014:

String dt = "12-17-2014"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148