简单的日历制作
1 import java.util.*; 2 import java.text.*; 3 class Demo 4 { 5 public static void main(String[] args) 6 { 7 long weekday = 0; 8 int c = 0; 9 Scanner scan = new Scanner(System.in); 10 String str = "1900-1-1";//1900-1-1是星期一 11 System.out.println("请输入年月(年-月):"); 12 String str1 = scan.next(); 13 String str2 = str1 + "-1";//为了和1900-1-1到输入的时间计算出差多少天而加上字符"-1" 14 String str3 = null; 15 long yearDays = charge(str,str2);//计算出1900-1-1到输入的时间相差的天数 16 weekday = yearDays%7+1;//计算出一号一星期几 17 System.out.println(weekday); 18 String str4 = str1.substring(5);//截取字符,截取到后面的月份 19 int num = 0; 20 num=Integer.valueOf(str4); 21 String str5 = str1.substring(0,4); 22 23 int num1 = 0; 24 num1 = Integer.valueOf(str5);//把截取到的字符月份转换为整形 25 switch (num) 26 { 27 case 1: 28 case 3: 29 case 5: 30 case 7: 31 case 8: 32 case 10: 33 case 12: 34 c = 31; 35 break; 36 case 4: 37 case 6: 38 case 9: 39 case 11: 40 c = 30; 41 break; 42 case 2: 43 { 44 //判断是否为闰年 45 if ((num1%4 == 0 && num1%100 != 0) || num1 % 400 ==0) 46 { 47 c = 29; 48 }else { 49 c = 28; 50 } 51 } 52 break; 53 } 54 System.out.println("星期日\t"+"星期一\t"+"星期二\t"+"星期三\t"+"星期四\t"+"星期五\t"+"星期六\t"); 55 if(weekday%7!=0){//判断星期天是不是一号,是就不打印*号 56 for (int i = 1; i <= weekday ; i++)//打印*号 57 { 58 59 System.out.print(" *"+"\t"); 60 61 } 62 } 63 int day=0; 64 for (int i = (int)weekday ; i < c+ (int)weekday ; i++ )//打印每天的号数 65 { 66 day++;//每天号数记录 67 if ((i) % 7 == 0) 68 { 69 System.out.println(); 70 } 71 System.out.print(" "+day+"\t"); 72 } 73 } 74 75 public static long charge(String date1,String date2){ 76 77 //做时间差 78 //将String转为Date做计算 79 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); 80 long charge = 0; 81 try{ 82 Date d1 = sd.parse(date1); 83 Date d2 = sd.parse(date2); 84 //时间也是以毫秒为单位。 85 charge = (d2.getTime() - d1.getTime()) / (1000*24*60*60); 86 }catch(ParseException e){ 87 System.out.println(e); 88 } 89 return charge; 90 } 91 }