javadatecalendarsimpledateformat

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);
setToDate(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -6);
setFromDate(sdf.format(cal.getTime()));

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


Solution

  • int daysBackToSat = cal.get(Calendar.DAY_OF_WEEK );
    
    cal.add(Calendar.DATE, daysBackToSat * -1);
    System.out.println(sdf.format(cal.getTime()));
    

    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 there is no "day 0", you subtract 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;
    }