Java Beginner Java Beginner - 3 months ago 10x
Java Question

Getting previous particular day in a week

I am using java date java.util.Calendar and java.text.SimpleDateFormat for my report page.

I want to always set the start date to previous saturday and end date to friday after that saturday.

I wrote a java code which checks this and does it as follows but I am sure its wrong logic wise

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
cal.add(Calendar.DATE, -6);

How to get previous FromDate(yyyy-mm-dd) and ToDate(yyyy-mm-dd) where FromDate should be last saturday and ToDate should be last friday.

Case 1

Case 2

int daysBackToSat = cal.get(Calendar.DAY_OF_WEEK );

cal.add(Calendar.DATE, daysBackToSat*-1);

in line 1 you get a number indicating the current day of the week. which is 1 for sunday ,7 for saturday, 6 for friday, etc. so say if it's Wednesday today you'll get a 4. since saturday is 7 and tehre is no "day 0", you substract 4 days from the current date (line 2). in order to get the next friday after your saturday, you just add 6 days.

EDIT: considering your update i see, that if it's wednesday you don't want to have the saturday before that, but 1 week earlier. if it's already saturday, you'll go back only 1 week. in that case you check, if the "daysBackToSat" is 7, then leave it that way, if it's less than 7 then add another 7 to it.

        if(daysBackToSat<7) {
            daysBackToSat += 7;