步骤:
1、首先画出基本日历
输入年份和月份后计算出月份的第一天为与该周的第几天
int w=cal.get(Calendar.DAY_OF_WEEK)-1;
int t = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //获取设置日历月份的最大天数
得到这两个条件就可以开始画日历
public static void Caleanday(String yeartime,String monthtime) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM",Locale.ENGLISH); Date day = sdf.parse(yeartime+"-"+monthtime+""+"-01"); Calendar cal = Calendar.getInstance(); cal.setTime(day); //判断当前月份第一天是这一周的第几天 int w=cal.get(Calendar.DAY_OF_WEEK)-1; /*if(w==0) { w=7; }*/ int t = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //获取设置日历月份的最大天数 // System.out.println(t); // int Day1 = cal.get(Calendar.DAY_OF_WEEK); // System.out.println(w); System.out.println("日"+"\t"+"一"+"\t"+"二"+"\t"+"三"+"\t"+"四"+"\t"+"五"+"\t"+"六"); switch(w){ case 1: System.out.print("\t"); break; case 2: System.out.print("\t"+"\t"); break; case 3: System.out.print("\t"+"\t"+"\t"); break; case 4: System.out.print("\t"+"\t"+"\t"+"\t"); break; case 5: System.out.print("\t"+"\t"+"\t"+"\t"+"\t"); break; case 6: System.out.print("\t"+"\t"+"\t"+"\t"+"\t"+"\t"); break; case 7: System.out.print(""); break; } int inter = w; int days = Sign(yeartime,monthtime); //计算输入月份距2020-02-02差多少天,来进行标记天数 int n = 0; //统计休息天数 int m = 0; //统计周末休息天数 for(int i=1; i<t+1; i++){ if(days%4 ==0 && (inter == 0 || inter == 6)){ m++; } if(days%4 ==0){ n++; System.out.print("["+i+"]"+"\t"); } else{ System.out.print(i+"\t"); } inter++; days++; if(inter == 7){ System.out.println("\n"); inter = 0; } } System.out.println("本月休息天数:"+n+"天"); System.out.println("本月周末休息天数:"+m+ "天"); }
画出日历后,需要对相应日期进行标记
在Calenday方法调用Sign方法:计算输入日期距离2020-02-02有多少天,用days天数%4求余,判断是否是每三天后的第一天;
public static int Sign(String yeartime,String monthtime) throws ParseException { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH); Date date1 = sdf.parse("2020-02-02"); Date date2 = sdf.parse(yeartime+"-"+monthtime+""+"-01"); int diffdays = differentDays(date1,date2); return diffdays; // System.out.println("\n"); // System.out.println("相差:"+days); } /* * 计算相差多少天 */ public static int differentDays(Date date1,Date date2) { int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24)); return days; }
在本次日历代码中所运用到的系统内部方法:
int w=cal.get(Calendar.DAY_OF_WEEK)-1; int t = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //获取设置日历月份的最大天数
用到3个日历对象:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM",Locale.ENGLISH); Date day = sdf.parse(yeartime+"-"+monthtime+""+"-01"); Calendar cal = Calendar.getInstance();
