import java.util.Calendar;
/*
* Calendar:它爲特定瞬間與一組諸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日曆字段之間的轉換提供了一些方法,併爲操作日曆字段(例如獲得下星期的日期)提供了一些方法。
* public int get(int field):返回給定日曆字段的值。日曆類中的每個日曆字段都是靜態的成員變量,並且是int類型。
*
* public void add(int field,int amount):根據給定的日曆字段和對應的時間,來對當前的日曆進行操作。
* public final void set(int year,int month,int date):設置當前日曆的年月日
*/
public class CalendarDemo {
public static void main(String[] args) {
// 獲取當前的日曆時間
Calendar c = Calendar.getInstance();
// 獲取年
int year = c.get(Calendar.YEAR);
// 獲取月
int month = c.get(Calendar.MONTH);
// 獲取日
int date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
// 5年後的10天前
c.add(Calendar.YEAR, 5);
c.add(Calendar.DATE, -10);
// 獲取年
year = c.get(Calendar.YEAR);
// 獲取月
month = c.get(Calendar.MONTH);
// 獲取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
System.out.println("--------------");
c.set(2011, 11, 11);
// 獲取年
year = c.get(Calendar.YEAR);
// 獲取月
month = c.get(Calendar.MONTH);
// 獲取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
}
}
import java.util.Calendar;
import java.util.Scanner;
/*
* 獲取任意一年的二月有多少天
*
* 分析:
* A:鍵盤錄入任意的年份
* B:設置日曆對象的年月日
* 年就是A輸入的數據
* 月是2
* 日是1
* C:把時間往前推一天,就是2月的最後一天
* D:獲取這一天輸出即可
*/
public class CalendarTest {
public static void main(String[] args) {
// 鍵盤錄入任意的年份
Scanner sc = new Scanner(System.in);
System.out.println("請輸入年份:");
int year = sc.nextInt();
// 設置日曆對象的年月日
Calendar c = Calendar.getInstance();
c.set(year, 2, 1); // 其實是這一年的3月1日
// 把時間往前推一天,就是2月的最後一天
c.add(Calendar.DATE, -1);
// 獲取這一天輸出即可
System.out.println(c.get(Calendar.DATE));
}
}