java实现当月日历功能

《java核心技术》笔记——java实现日历功能

java实现当月日历功能_第1张图片
要点

  • 确定今天的月份和日
  • 确定本月的第一天
  • 确定本月第一天是周几 第一天前面填充空格,间隔用空格或星号,
  • 周日后换行
package com.company;

import java.time.DayOfWeek;
import java.time.LocalDate;

public class Main {

    public static void main(String[] args) {
	// write your code here
        LocalDate date = LocalDate.now();
        int month = date.getMonthValue();   //获得月份
        int today = date.getDayOfMonth();
        //System.out.println(date.getDayOfWeek().getValue());

        date = date.minusDays(today - 1);   //set to start of month today-1表示时间间隔,减去指定的天数
        DayOfWeek weekday = date.getDayOfWeek();
        int value = weekday.getValue(); //1 = Monday,...7 = Sunday

        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();
    }
}

你可能感兴趣的:(java)