Java Date - 달력 날짜 출력하기

달력을 만들어 보는 시간이다.
실행 결과를 보고 자바로 출력한다.

자바 실행 예상 결과

년도: 2025
월을 입력하세요: 1
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25 
26 27 28 29 30 31
년도: 2025
월을 입력하세요: 6
Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31

풀이

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int cnt = 0;
        int[][] calenders = new int[6][7];


        // 사용자 입력 대기
        System.out.print("년도: ");
        int year = sc.nextInt();
        sc.nextLine();
        System.out.print("월: ");
        int month = sc.nextInt();
        sc.nextLine();

        LocalDate calDate = LocalDate.of(year, month, 1);
        int lastDay = calDate.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
        int today = calDate.get(ChronoField.DAY_OF_WEEK);
        DayOfWeek firstWeek= calDate.getDayOfWeek();

        // 데이터 할당
        for (int i = 0, j = today; i < calenders.length; i++) {
            for (; j < calenders[i].length; j++) {
                calenders[i][j] = ++cnt;
                if (cnt == lastDay) {
                    i = calenders.length;
                    break;
                }
            }
            j = 0;
        }

        // Display
        System.out.println("Su Mo Tu We Th Fr Sa");
        for (int[] calender : calenders) {
            for (int c : calender) {
                if (c == 0) System.out.print("   ");
                else System.out.printf("%2d ", c);
            }
            System.out.println();
        }
    }
}

출력

년도: 2025
월: 1
Su Mo Tu We Th Fr Sa
          1  2  3  4 
 5  6  7  8  9 10 11 
12 13 14 15 16 17 18 
19 20 21 22 23 24 25 
26 27 28 29 30 31    

개선된 코드

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int cnt = 0;
        int[][] calenders = new int[6][7];


        System.out.print("년도: ");
        int year = sc.nextInt();
        sc.nextLine();
        System.out.print("월: ");
        int month = sc.nextInt();
        sc.nextLine();

        LocalDate firstDayOfMonth = LocalDate.of(year, month, 1);
        LocalDate firstDayOfNextMonth = firstDayOfMonth.plusMonths(1);

        // 일=0, 월=1, 화=2... 토=6 (10 % 7 = 3 수요일)
        // 달력의 첫번재 비어있는 항목 채우기
        int offsetWeekDays = firstDayOfMonth.getDayOfWeek().getValue() % 7;

        System.out.println("Su Mo Tu We Th Fr Sa ");

        for (int i = 0; i < offsetWeekDays; i++) {
            System.out.print("   ");
        }

        LocalDate dayIterator = firstDayOfMonth;
        while (dayIterator.isBefore(firstDayOfNextMonth)) {
            System.out.printf("%2d ", dayIterator.getDayOfMonth());
            if (dayIterator.getDayOfWeek() == DayOfWeek.SATURDAY) {
                System.out.println();
            }
            // 다음 날짜로 이동
            dayIterator = dayIterator.plusDays(1);
        }

    }
}

규칙적이지 않은 날짜부터 시작해 while 반복문은 LocalDate 객체의 plusDays 하루씩 증가시키며 다음 월까지 반복하여 코드를 동작시키고 있다.