Java基础IO输入输出04 发表于 2016-11-16 | Calendar对象导语: 学习的目的:不是掌握对象的方法,而是要学会如何使用API、如何使用API中的对象实现一些小功能,方法只需简单记下用什么对象就可以了。 类Calendar12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061/*Calendar对象另请参见:DateFormat、Calendar、TimeZone*/import java.util.*;import java.text.*;class CalendarDemo { public static void main(String[] args){ //方法一: Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String year = sdf.format(d);//返回的是字符串,我想加一年或减一年比较麻烦 System.out.println(year); //方法二: Calendar c = Calendar.getInstance(); //用查表法来改写 String[] mons = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"}; int index = c.get(Calendar.MONTH); String[] weeks = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; int index1 = c.get(Calendar.DAY_OF_WEEK); sop(c.get(Calendar.YEAR)+"年"); //sop((c.get(Calendar.MONTH)+1)+"月"); sop(mons[index]); sop(c.get(Calendar.DAY_OF_MONTH)+"日"); //sop("星期"+c.get(Calendar.DAY_OF_WEEK)); sop(weeks[index1]); //一些方法 Calendar c1 = Calendar.getInstance(); //c1.set(2012,2,23); //时间量的偏移 c1.add(Calendar.YEAR,4);//加4年 printCalendar(c1); } public static void sop(Object obj){ System.out.println(obj); } public static void printCalendar(Calendar c){ //用查表法来改写 String[] mons = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"}; int index = c.get(Calendar.MONTH); String[] weeks = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; int index1 = c.get(Calendar.DAY_OF_WEEK); sop(c.get(Calendar.YEAR)+"年"); //sop((c.get(Calendar.MONTH)+1)+"月"); sop(mons[index]); sop(c.get(Calendar.DAY_OF_MONTH)+"日"); //sop("星期"+c.get(Calendar.DAY_OF_WEEK)); sop(weeks[index1]); }}