Calendar日历类
Calendar类是一个抽象类,为我们提供了关于计算的功能,比如:年、月、日
时、分、秒的展示和计算。
GregorianCalendar是Calendar的子类,表示公历
菜鸟雷区
注意月份的表示,一月是0,二月是1,以此类推,12是11.因为大多数人习惯于
使用单词而不是使用数字来表示月份,这样程序也许更易读,父类Calendar使用
常量来表示月份:JANUARY,FEBRUARYD等等。
package com.itbaizhan; import java.util.*; //测试DateFormat public class TestDateFormat { public static void main(String[] args) { GregorianCalendar calendar=new GregorianCalendar (2049,9,1,22,10,50); //System.out.println(calendar); printCalendar(calendar); int year =calendar.get(Calendar.YEAR); //打印:2049 int month=calendar.get(Calendar.MONTH); //打印:10 int day=calendar.get(Calendar.DAY_OF_MONTH); //打印10 int day2=calendar.get(Calendar.DATE); //打印9 //日:Calendar.DATE和Calendar.DAY_OF_MONTH同义 int date=calendar.get(Calendar.DAY_OF_WEEK); //打印3 //星期几 这里是:1-7.周日是1,周一是2 周六是7 System.out.println(year); System.out.println(month); System.out.println(day); System.out.println(day2); System.out.println(date); GregorianCalendar calendar2=new GregorianCalendar(); calendar2.set(Calendar.YEAR,2049); calendar2.set(Calendar.MONTH,Calendar.OCTOBER); //月份0-11 calendar2.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,50); calendar3.add(Calendar.MONTH,-7); calendar3.add(Calendar.DATE,7); printCalendar(calendar3); GregorianCalendar calendar4=new GregorianCalendar(); calendar4.setTime(new Date()); printCalendar(calendar4); } 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+"秒"); //System.out.println("%d年%d月%d日,星期%s %d:%d:%d\n", year,month,day,week,hour,minute,second); } }