13-07 Java語言基礎(常用工具類之Calendar類)
阿新 • • 發佈:2020-12-29
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