java - to get the start date and end date of each week for the given month

前端 未结 3 618
暗喜
暗喜 2021-01-06 12:03

Following is the code that I am using to calculate the week start date and end date for the given month. Assume week start day is MONDAY and week end day is SUNDAY. For exa

3条回答
  •  误落风尘
    2021-01-06 12:16

    I get the answer with the following code

    List> getNumberOfWeeks(int year, int month) {
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            List> weekdates = new ArrayList>();
            List dates;
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, month);
            c.set(Calendar.DAY_OF_MONTH, 1);
            while (c.get(Calendar.MONTH) == month) {
                    dates = new ArrayList();
                  while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
                    c.add(Calendar.DAY_OF_MONTH, -1);
                  }
                  dates.add(format.format(c.getTime()));
                  c.add(Calendar.DAY_OF_MONTH, 6);
                  dates.add(format.format(c.getTime()));
                  weekdates.add(dates);
                  c.add(Calendar.DAY_OF_MONTH, 1);
            }
            System.out.println(weekdates);
            return weekdates;
          }
    

提交回复
热议问题