简体   繁体   中英

calendar month and year before

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM