1

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.

Joe Doyle
  • 6,363
  • 3
  • 42
  • 45
user710818
  • 23,228
  • 58
  • 149
  • 207

3 Answers3

3

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);
CamelSlack
  • 573
  • 2
  • 7
1

Even simpler would be to set the weekday directly:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DATE, -7);
System.out.println(cal.getTime());

Please keep in mind, that this does not effect the time. If you want 00:00, you need to set the appropriate values:

cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dave
  • 1,314
  • 1
  • 11
  • 18
1

java.time

Use a TemporalAdjuster.

LocalDate today = LocalDate.now();

LocalDate previousOrSameMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );

And subtract a week to get a second one.

LocalDate secondMondayBefore = previousOrSameMonday.minusWeeks( 1 );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154