1 public class Demo9_Calendar { 2 3 /* 4 * A:Calendar是一个抽象类 5 * B:成员方法 6 * public static Calendar getInstance() 7 * public int get(int field) 8 * C:成员方法 9 * public void add(int field, int amount) 对指定的字段进行向前或向后加或减 10 * public final void set(int year, int month, int date) 对指定字段进行修改 11 */ 12 public static void main(String[] args) { 13 14 //demo1(); 15 Calendar c = Calendar.getInstance(); 16 c.add(Calendar.MONTH, -1); //月份减1 17 c.set(Calendar.YEAR, 2088); //年份修改为2088 18 System.out.println(c.get(Calendar.YEAR) + "年" + getNum(c.get(Calendar.MONTH) + 1) + "月" 19 + getNum(c.get(Calendar.DAY_OF_MONTH)) + "日" + getWeek(c.get(Calendar.DAY_OF_WEEK))); 20 21 22 } 23 24 public static void demo1() { 25 Calendar c = Calendar.getInstance(); //相当于父类引用指向子类对象 26 System.out.println(c.get(Calendar.YEAR)); 27 System.out.println(c.get(Calendar.MONTH)); //月份是从0开始的 28 System.out.println(c.get(Calendar.DAY_OF_MONTH)); 29 System.out.println(c.get(Calendar.DAY_OF_WEEK)); //周日是第一天 30 System.out.println(c.get(Calendar.YEAR) + "年" + getNum(c.get(Calendar.MONTH) + 1) + "月" 31 + getNum(c.get(Calendar.DAY_OF_MONTH)) + "日" + getWeek(c.get(Calendar.DAY_OF_WEEK))); 32 } 33 34 /** 35 * 将星期存储表中进行查表 36 * @param week 37 * @return 38 */ 39 public static String getWeek(int week) { 40 String[] arr = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; 41 return arr[week]; 42 } 43 44 /** 45 * @param num 46 * @return String 47 */ 48 public static String getNum(int num) { 49 /*if (num < 10) { 50 return "0" + num; 51 }else { 52 return "" + num; 53 }*/ 54 return num > 9 ? "" + num : "0" + num; 55 } 56 }
利用Calendar类计算某一年是否是闰年:
1 /* 2 * 给定一个年份,判断是否是闰年 3 * 1.提示键盘输入年份 4 * 2.创建Calendar对象 5 * 3.通过set方法将日期设置为哪一年的3月1日 6 * 4.将日减1 7 * 5.判断日是否是29,得到结果 8 */ 9 public static void main(String[] args) { 10 11 Scanner sc = new Scanner(System.in); 12 System.out.println("请输入需要判断的年份:"); 13 // int year = sc.nextInt(); 14 // System.out.println(getYear(year)); 15 16 //优化,判断输入是否是4位数字字符串 17 int year = 0; 18 String s = sc.nextLine(); 19 String regex = "\d{4}"; 20 if (s.matches(regex)) { 21 year = Integer.parseInt(s); 22 System.out.println(getYear(year)); 23 24 }else { 25 System.out.println("输入有误!"); 26 } 27 28 } 29 30 public static boolean getYear(int year) { 31 Calendar c = Calendar.getInstance(); 32 c.set(year, 2, 1); 33 c.add(Calendar.DAY_OF_MONTH, -1); 34 System.out.println(c.get(Calendar.DAY_OF_MONTH)); 35 return c.get(Calendar.DAY_OF_MONTH) == 29; 36 }