Drickuss Merguez Drickuss Merguez - 6 months ago 14
Javascript Question

How to add days in java?

I am new in Java. I am trying to add some days depending on the selected item from a spinner but it seems like there is a mistake.

The values in the spinner are:

Today
,
Tomorrow
,
After two days
,
After three days
. Can anybody help me please?

It works perfectly for

Case 0: "Today"; it displays the current date, but for the rest it doesnt work.

Thanks!

date_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Calendar c = Calendar.getInstance();
rowvalue = parent.getItemAtPosition(position).toString();
switch (position){
case 0:
selectedDay = new SimpleDateFormat("yy/MM/dd").format(Calendar.getInstance().getTime());
break;
case 1:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 1);
break;
case 2:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 2);
break;
case 3:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 3);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});

Answer

The entire switch is unnecessary. You say case 0 is working, so I guess you want selectedDay to be the result of format. So remove the switch entirely and replace it with:

if (position >= 1 && position <= 3) {
    c.add(Calendar.DAY_OF_MONTH, position);
}
selectedDay = new SimpleDateFormat("yy/MM/dd").format(c.getTime());

Calendar#add modifies the calendar instance; then we use that when formatting for selectedDay.