Drickuss Merguez Drickuss Merguez - 1 year ago 71
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:

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.


date_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
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());
case 1:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 1);
case 2:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 2);
case 3:
selectedDay = c.add(Calendar.DAY_OF_MONTH, 3);
public void onNothingSelected(AdapterView<?> parent) {}

Answer Source

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.