본문 바로가기

카테고리 없음

JAVA 특정 월 주마다 날짜 가져오기

년도와 월을 인자로 받아 해당 년월의 주차 정보를 보여준다.

   	public void findWeekWithYearAndMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();

        int overWeek = 0;
        for (int week = 1; week < cal.getMaximum(Calendar.WEEK_OF_MONTH); week++) {
            cal.set(Calendar.YEAR, year); // 년도 세팅
            cal.set(Calendar.MONTH, month - 1); // 월 세팅 (Calendar는 0~11이기 때문에 -1 해줌)
            cal.set(Calendar.WEEK_OF_MONTH, week); // 주차 세팅

            cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); // 목요일로 이동

            int thursDayMonth = cal.get(Calendar.MONTH) + 1; // 세팅된 Calendar의 월을 가져옴
            if (thursDayMonth < month) { // 목요일로 이동했을 때 cal의 월이 입력으로 들어온 월(month)보다 작으면 한주 넘김
                overWeek++;
                continue;
            } else if (thursDayMonth > month) { // 목요일로 이동했을 때 cal의 월이 입력으로 들어온 월(month)보다 크면 넘김(종료)
                continue;
            }

            System.out.print(year + "년 " + month + "월 " + (week - overWeek) + "주차 :");
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 월요일로 이동
            LocalDate startDate = LocalDate.ofInstant(cal.toInstant(), ZoneId.systemDefault()); // 날짜 가져오기
            System.out.print(startDate + " ~ ");

            cal.add(Calendar.WEEK_OF_MONTH, 1);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 일요일로 이동
            LocalDate endDate = LocalDate.ofInstant(cal.toInstant(), ZoneId.systemDefault()); // 날짜 가져오기
            System.out.println(endDate);


        }

    }