一:引言
代码当中注释很详尽,直接上码;
二:上码
package cn.wyj.one;import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;public class Demo3_打印日历 {public static void main(String[] args) throws ParseException {System.out.println("请输入日期:");Scanner in = new Scanner(System.in);//将字符串 设置成日期类String str = in.nextLine();DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//将时间对象格式化Date date = df.parse(str);// <=> Date date = df.parse("2021-7-13"); 这里的参数格式与上方设置的参数格式要相同//System.out.println(date);Calendar c = new GregorianCalendar();c.setTime(date);//System.out.println(c);int day = c.get(Calendar.DATE);System.out.println("日\t一\t二\t三\t四\t五\t六");c.set(Calendar.DATE,1);//表示从1号开始//这里是规范设置1号是星期几int a = c.get(Calendar.DAY_OF_WEEK);//System.out.println(a);for(int i = 0; i < a-1; i++){System.out.print("\t");}int b = c.getActualMaximum(Calendar.DATE);//这里的参数不能是(c.get(Calendar.MONTH));for(int i = 1; i <= b; i++ )//c.getActualMaximum(Calendar.DATE) 是获取这个月当中的最大值{if( day == c.get(Calendar.DATE)){System.out.print(c.get(Calendar.DAY_OF_MONTH)+"*\t");}else{System.out.print(c.get(Calendar.DAY_OF_MONTH)+"\t");}if(c.get(Calendar.DAY_OF_WEEK)== 7){//也就是周六 就换行()System.out.println();}c.add(Calendar.DAY_OF_MONTH, 1);//每次循环加一天}}}