Calendar 类是一个抽象类,为我们提供了关于日期计算的功能,比如:年、月、日、时、分、秒的展示和计算。
GregorianCalendar 是Canlendar 的子类,表示公历。
注:月份的表示,一月是0,二月是1,以此类推,十二月是11。因为大多数人习惯于使用单词而不是使用数字来表示月份,这样程序也许更易读,父类Canlenar 使用常量来表示月份:JANUARY、FEBRUARY等等。
GregorianCalendar 类和 Canlendar 类的使用:
import java.util.*;public class TestCalendar {public static void main(String[] args){//得到相关日期元素GregorianCalendar calendar = new GregorianCalendar(2049,9,1,22,10,50);int year = calendar.get(Calendar.YEAR); //打印:2049int month = calendar.get(Calendar.MONTH); //打印:9int day = calendar.get(Calendar.DAY_OF_MONTH); //打印:1int day2 = calendar.get(Calendar.DATE); //打印:1//日:Calendar.DATE 和 Calendar.DAY_OF_MONTH 同义int date = calendar.get(Calendar.DAY_OF_WEEK); //打印:1//星期几 这里是:1-7,周日是1,周一是2...周六是7System.out.println(year);System.out.println(month);System.out.println(day);System.out.println(day2);System.out.println(date);//设置日期GregorianCalendar calendar2 = new GragorianCalendar();calendar2.set(Calendar.YEAR,2049);calendar2.set(Calendar.MONTH,Calendar.OCTOBER); //月份数:0-11calendar2.set(Calendar.DATE,1);calendar2.set(Calendar.HOUR_OF_DAY,10);calendar2.set(Calendar.MINUTE,20);calendar2.set(Calendar.SECOND,23);printCalendar(calendar2);//日期计算GregorianCalendar calendar3 = new GregorianCalendar(2049,9,1,22,10);calendar3.add(Calendar.MONTH,-7); //月份减7calendar3.add(Calendar.DATE,7); //增加7天//日历对象和时间对象转化Date d = calendar3.getTime();GregorianCalendar calendar4 = new GregorianCalendar();calendar4.setTime(new Date());}static void printCalendar(Calendar calendar){int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1;int day = calendar.get(Calendar.DAY_OF_MONTH); int date = calendar.get(Calendar.DAY_OF_WEEK) - 1; //星期几String week = "" + ((date == 0) ? "日" : date);int hour = calendar.get(Calendar.HOUR);int minute = calendar.get(Calendar.MINUTE);int second = calendar.get(Calendar.SECOND);System.out.println(year+"年"+month+"月"+day+"日,"+"星期"+week+hour+"时"+minute+"分"+second+"秒");}
}