How to print a calendar for a specific month and year in Java

1 Answer

0 votes
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;

public class MonthCalendar {

    public static void printMonth(int year, int month) {
        YearMonth ym = YearMonth.of(year, month);
        LocalDate first = ym.atDay(1);

        System.out.printf("     %s %d%n", ym.getMonth(), year);
        System.out.println("Su Mo Tu We Th Fr Sa");

        int firstDow = first.getDayOfWeek().getValue(); // Monday=1 ... Sunday=7
        int offset = firstDow % 7; // convert so Sunday=0

        for (int i = 0; i < offset; i++)
            System.out.print("   ");

        for (int day = 1; day <= ym.lengthOfMonth(); day++) {
            System.out.printf("%2d ", day);
            if ((offset + day) % 7 == 0)
                System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        printMonth(2026, 1);
    }
}



/*
run:

     JANUARY 2026
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 

*/

 



answered Jan 18 by avibootz

Related questions

...