0

I am hitting an issue and want some help in one more.

Below is my code block -

public Date addDays(Date date, int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); //minus number would decrement the days
        return cal.getTime();
    }


StartDate = "02/06/2016";
DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
for (int i=0; i < 90; i++) {
                try{
                    rawStartDate = df.parse(StartDate);
                    formattedStartDate = df.format(rawStartDate);
                    String timeBookedForPerDay = startHour + ":" + startMin + ":" + startSlot + "-"
                            + endHour + ":" + endMin + ":" + endSlot;
                    bookedFor.put(formattedStartDate, timeBookedForPerDay);
                    rawNextDate = addDays(rawStartDate, 1);
                    StartDate = df.format(rawNextDate);
                }
                catch ( Exception ex ){
                }
            }

Now the issue i am hitting is, till the time the month is february adding one day is working fine iteratively. However when the month should change, it starts iterating on the same month.

Also adding the day to the date is not taking care of the number of days in month i.e. 29 in Feb and 31 in march.

Any pointers, what can be a better way.

Output is (Truncated a bit) -

***Start Date***03/01/2016
***Start Date***03/02/2016
***Start Date***03/03/2016
***Start Date***03/04/2016
***Start Date***03/05/2016
***Start Date***03/06/2016
***Start Date***03/07/2016
***Start Date***03/08/2016
***Start Date***03/09/2016
***Start Date***03/10/2016
***Start Date***03/11/2016
***Start Date***03/12/2016
***Start Date***03/13/2016
***Start Date***03/14/2016
***Start Date***03/15/2016
***Start Date***03/16/2016
***Start Date***03/17/2016
***Start Date***03/18/2016
***Start Date***03/19/2016
***Start Date***03/20/2016
***Start Date***03/21/2016
***Start Date***03/22/2016
***Start Date***03/23/2016
***Start Date***03/24/2016
***Start Date***03/25/2016
***Start Date***03/26/2016
***Start Date***03/27/2016
***Start Date***03/28/2016
***Start Date***03/29/2016
***Start Date***03/30/2016
***Start Date***03/31/2016
***Start Date***03/01/2016
***Start Date***03/02/2016
***Start Date***03/03/2016
***Start Date***03/04/2016
***Start Date***03/05/2016
***Start Date***03/06/2016

Any suggestions or pointers or any duplicate question i can refer?

Thanks,

AJ

AJ84
  • 175
  • 1
  • 19

1 Answers1

3

in SimpleDateFormat mm is for minute MM is for month, your date(month) is updating but you dont see it, what you see is minute, so you should edit your format pattern like

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
guleryuz
  • 2,714
  • 1
  • 15
  • 19