Calendar类
概述:
Calendar类是一个抽象类,它为特定瞬间与一组诸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日历字段之间的转换
成员方法:
public static Calendar getInstance()
public int get(int field)
代码:
import java.util.Calendar;
public class Demo10_Calendar {
public static void main(String[] args) {
Calendar c = Calendar.getInstance(); //父类引用指向子类对象
// System.out.println(c.get(Calendar.YEAR));
// System.out.println(getNum(c.get(Calendar.MONTH))); //月份按照0开始编号
// System.out.println(getNum(c.get(Calendar.DAY_OF_MONTH)));
// System.out.println(getWeek(c.get(Calendar.DAY_OF_WEEK))); //周日是第一天,周六是最后一天
System.out.println(c.get(Calendar.YEAR) + "年" + getNum(c.get(Calendar.MONTH) + 1) + "月"
+ getNum(c.get(Calendar.DAY_OF_MONTH)) + "日" + getWeek(c.get(Calendar.DAY_OF_WEEK)));
}
// 将星期存储表中进行查表
public static String getWeek(int week) {
String[] arr = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
return arr[week];
}
//数字最少两位,不足两位前面补0
public static String getNum(int num) {
// String s = Integer.toString(num);
// if(s.length() < 2) {
// StringBuffer sb = new StringBuffer(s);
// sb.insert(0, "0");
// s = sb.toString();
// }
// return s;
// if(num > 9) {
// return "" + num;
// }else {
// return "0" + num;
// }
return num > 9? "" + num : "0" + num;
}
}
输出:
2020年12月28日星期一
Calendar的add()和set()方法:
import java.util.Calendar;
public class Demo11_Calendar {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, 1); //对指定的字段向前加,或者向后减
c.add(Calendar.MONTH, 1);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
c.set(Calendar.YEAR, 2000);
System.out.println(c.get(Calendar.YEAR));
c.set(2000, 7, 8);
System.out.println(c.get(Calendar.YEAR) + "年" + (c.get(Calendar.MONTH) + 1) + "月"
+ c.get(Calendar.DAY_OF_MONTH) + "日");
}
}
输出:
2022
0
2000
2000年8月8日
Calendar类来判断闰年和平年
import java.util.Calendar;
public class Demo12_Calendar {
public static void main(String[] args) {
System.out.println(isLeap2(2000));
}
//判断是否闰年--普通方法
public static boolean isLeap1(int year) {
if(year % 400 == 0) {
return true;
}else if(year % 4 ==0 && year % 100 != 0){
return true;
}else {
return false;
}
}
//判断是否闰年--Calendar类
public static boolean isLeap2(int year) {
Calendar c = Calendar.getInstance();
// c.set(Calendar.MONTH, 2);
// c.set(Calendar.DAY_OF_MONTH, 1); //设置为该年的3月1日
c.set(year, 2, 1); //设置为该年的3月1日
c.add(Calendar.DAY_OF_MONTH, -1); //日向前减1
return c.get(Calendar.DAY_OF_MONTH) == 29; //如果2月有29号的话,代表是闰年
}
}
输出:
true