[Java Core Technology (Volume I)]-Simple Calendar

Reference-P102~P103

1. Goal

Generate a calendar, the format is as shown in the figure below.
Insert picture description here

ps: The current number of days needs to be marked as *

2. Core

Variables to the calendar

import java.time.*;
public class CalendarTest{
    
    
    public static void main(String[] args) {
    
    
        LocalDate date = LocalDate.now();	// 获取当前日期
        int month = date.getMonthValue();	// 获取当前月份
        int today = date.getDayOfMonth();   // 获取当前的天数
        date = date.minusDays(today - 1);	// 将当前日期设置为月初

        while(date.getMonthValue() == month) {
    
    		// 只要是当月就输出,否则跳出循环
            System.out.printf("%3d", date.getDayOfMonth());
            date = date.plusDays(1);
        }
    }
}

Insert picture description here

3. Realization

In the core part, the circular printing of the calendar is realized, and then only the header, current date and line break need to be completed.

import java.time.*;

public class CalendarTest{
    
    
    public static void main(String[] args) {
    
    
        LocalDate date = LocalDate.now();
        int month = date.getMonthValue();
        int today = date.getDayOfMonth();

        date = date.minusDays(today - 1);       // 设置为本月的开头
        DayOfWeek  weekday = date.getDayOfWeek();     // 获取星期几
        int value = weekday.getValue();     // 将星期几兑换成对应的数字

        System.out.println("Mon Tue Wed Thu Fri Sat Sun");  // 日历头
        for(int i = 1; i < value; i++) {
    
        // 打印对应的空格
            System.out.print("    ");
        }
        
        while(date.getMonthValue() == month) {
    
    
            System.out.printf("%3d", date.getDayOfMonth());     // 获取当前多少号

            if(date.getDayOfMonth() == today) {
    
    
                System.out.print("*");
            } else {
    
    
                System.out.print(" ");
            }
            date = date.plusDays(1);
            if(date.getDayOfWeek().getValue() == 1){
    
    
                System.out.println();
            }
        }
        if (date.getDayOfWeek().getValue() != 1) System.out.println();
    }
}

Guess you like

Origin blog.csdn.net/piano9425/article/details/109713532