Java Data Type How to - Get all dates of sundays in a particular year








Question

We would like to know how to get all dates of sundays in a particular year.

Answer

import java.util.Calendar;
import java.util.GregorianCalendar;
/*from   ww  w  .  j  a v  a2 s  .  com*/
public class Main {
  public static void main(String[] args) {
    int dayOfWeek = Calendar.SUNDAY;
    Calendar cal = new GregorianCalendar();
    cal.set(2015, 0, 1, 0, 0);
    cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
    while (cal.get(Calendar.YEAR) == 2015) {
      System.out.println(cal.getTime());
      cal.add(Calendar.DAY_OF_MONTH, 7);
    }
  }
}

The code above generates the following result.