user710818 user710818 - 15 days ago 5
Java Question

How in Java find dates for previous 2 mondays?

May be like this:

for(int i=0;i<15;i++){
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -1);

if (cal.Calendar.DAY_OF_WEEK==1){
System.out.println(cal.cal.getTime())


But may be exists more simple way?
Thanks.

Answer

You are on the right track.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -7); // First week before
cal.add(Calendar.DAY_OF_YEAR, -7); // Second week before

Let me make this work for just Mondays.

Calendar cal = Calendar.getInstance();

int weekday = cal.get(Calendar.DAY_OF_WEEK);
int days = (Calendar.SATURDAY - weekday + 2) % 7;

cal.add(Calendar.DAY_OF_YEAR, days);

cal.add(Calendar.DAY_OF_MONTH, -7);
cal.add(Calendar.DAY_OF_MONTH, -7);
Comments