Java基础IO输入输出04

Calendar对象

导语:

学习的目的:不是掌握对象的方法,而是要学会如何使用API、如何使用API中的对象实现一些小功能,方法只需简单记下用什么对象就可以了。

类Calendar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
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]);
}
}