0

I have to put a date one week before and then 1 month before. If i try with the days one week before is working but if the day es 5 and it has to change the month is not working, it changes me the year instead. About the month it changes me the year tring addUrl = "";

    SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
    // surround below line with try catch block as below code throws checked
    // exception
    Date endDate = sdf.parse(request.getParameter(field.getId()));
    Calendar cal = DateToCalendar(endDate);
    cal.setTime(endDate);

    SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");

    case "day":
        cal.add(Calendar.DATE, -1);

        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
        break;

    case "week":
        cal.add(Calendar.DATE, -6); // number of days to add
        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
        break;

    default:
        cal.add(Calendar.MONTH, -1); // number of days to add
        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;

    }

How i can do that?

Thanks

  • possible duplicate of [Java - Subtract Days from date](http://stackoverflow.com/questions/12930134/java-subtract-days-from-date) – Basil Bourque Nov 28 '14 at 01:16

2 Answers2

1

In your SimpleDateFormat objects, you should use MM for months and not mm, because mm means minutes, not months.

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

SimpleDateFormat formatToSend = new SimpleDateFormat("yyyy-MM-dd");

See the API documentation of java.text.SimpleDateFormat.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

Im not sure do i fully understand the question however one potential problem is in your date format

m = Minute in hour

M = Month in year <- maybe the one you want?

See here for more examples.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

BrendanM
  • 383
  • 3
  • 14