列舉Java日歷類Calendar的一些常用方法
在開發(fā)時(shí)關(guān)于日期的用處很多,此處列舉一些常用的方法。
對(duì)于字符串類型的日期"yyyy-mm-dd"和對(duì)Calendar類型日期的處理。
1
/**
2
* 將yyyy-mm-dd格式的字符串日期轉(zhuǎn)換為Calendar對(duì)象
3
* @param str String
4
* @reurn Calendar
5
*/
6
public Calendar getCalendarDate(String str) throws Exception
7
{
8
//Calendar c = Calendar.getInstance();
9
tmp.setTime( new SimpleDateFormat("yyyy-MM-dd").parse(str));
10
11
return tmp;
12
}
13
14
/**
15
* 返回輸入的Calendar日期所在星期的星期一的日期
16
* @param c Calendar
17
* @return String (yyyy-mm-dd)
18
*/
19
public String getFirstDayOfWeek(Calendar c)
20
{
21
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd");
22
23
c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
24
return formatter.format(tmp.getTime());
25
}
26
27
/**
28
* 返回輸入的Calendar日期所在月的第一天的日期
29
* @param c Calendar
30
* @return String (yyyy-mm-dd)
31
*/
32
public String getFirstDayOfMonth(Calendar c)
33
{
34
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd");
35
36
int year = c.get(c.YEAR);
37
int month = c.get(c.MONTH);
38
int day = 1;
39
c.set(year, month, day);
40
return formatter.format(tmp.getTime());
41
}
42
43
/**
44
* 返回該日期的年份
45
* @param str String (yyyy-mm-dd)
46
* @return int
47
* @throws Exception
48
*/
49
public int getYear(String str) throws Exception
50
{
51
Calendar t = Calendar.getInstance();
52
t.setTime( new SimpleDateFormat("yyyy-MM-dd").parse(str));
53
return t.get(t.YEAR);
54
}
55
56
/**
57
* 返回該日期的月份
58
* @param str String (yyyy-mm-dd)
59
* @return int
60
* @throws Exception
61
*/
62
public int getMonth(String str) throws Exception
63
{
64
Calendar t = Calendar.getInstance();
65
t.setTime( new SimpleDateFormat("yyyy-MM-dd").parse(str));
66
return t.get(t.MONTH)+1;
67
}
68
69
/**
70
* 返回該日期所在星期是該月的第幾個(gè)星期
71
* @param str String (yyyy-mm-dd)
72
* @return int
73
* @throws Exception
74
*/
75
public int getWeekNumInMonth(String str) throws Exception
76
{
77
Calendar t = Calendar.getInstance();
78
t.setTime( new SimpleDateFormat("yyyy-MM-dd").parse(str));
79
return t.get(t.WEEK_OF_MONTH);
80
}

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

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

posted on 2009-07-09 15:37 此號(hào)已被刪 閱讀(1266) 評(píng)論(0) 編輯 收藏 所屬分類: JAVA