public static void displayCalendarRange(int month, int year) {
// Lấy thông tin tháng trước, hiện tại, và tháng sau
YearMonth currentMonth = YearMonth.of(year, month);
YearMonth previousMonth = currentMonth.minusMonths(1);
YearMonth nextMonth = currentMonth.plusMonths(1);
// Hiển thị lịch của từng tháng
System.out.println("\n--- Calendar for " + previousMonth.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH) + " " + previousMonth.getYear() + " ---");
printMonthCalendar(previousMonth);
System.out.println("\n--- Calendar for " + currentMonth.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH) + " " + currentMonth.getYear() + " ---");
printMonthCalendar(currentMonth);
System.out.println("\n--- Calendar for " + nextMonth.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH) + " " + nextMonth.getYear() + " ---");
printMonthCalendar(nextMonth);
}
private static void printMonthCalendar(YearMonth yearMonth) {
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstDayOfMonth = yearMonth.atDay(1);
// Lấy ngày bắt đầu (thứ trong tuần) của tháng
int startDayOfWeek = firstDayOfMonth.getDayOfWeek().getValue(); // 1 = Monday, ..., 7 = Sunday
// Tiêu đề tuần
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
// In khoảng trắng trước ngày đầu tiên
for (int i = 1; i < startDayOfWeek; i++) {
System.out.print(" ");
}
// In các ngày trong tháng
for (int day = 1; day <= daysInMonth; day++) {
System.out.printf("%3d ", day);
// Xuống dòng khi hết tuần (chủ nhật)
if ((startDayOfWeek + day - 1) % 7 == 0) {
System.out.println();
}
}
System.out.println(); // Dòng trống cuối tháng
}
public static void main(String[] args) {
// Ví dụ: Hiển thị lịch từ tháng 3/2025
displayCalendarRange(3, 2025);
}