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,303
  • 3
  • 42
  • 45
user710818
  • 21,911
  • 55
  • 143
  • 199

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
  • 563
  • 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,174
  • 1
  • 8
  • 15
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
  • 262,936
  • 84
  • 758
  • 1,028