Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 856
Java Beginner Avatar asked Jun 21 '13 07:06

Java Beginner


2 Answers

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 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;
        }
like image 144
tagtraeumer Avatar answered Nov 07 '22 12:11

tagtraeumer


I recently developed Lamma Date, which is very good to serve this use case.

    Date today = new Date(2014, 7, 1);

    Date to = today.previous(DayOfWeek.FRIDAY);  // Date(2014,6,27)
    Date from = to.previous(DayOfWeek.SATURDAY); // Date(2014,6,21)
like image 1
Max Avatar answered Nov 07 '22 12:11

Max