Java Reference
In-Depth Information
3
public class
TestCalendar {
4
public static void
main(String[] args) {
5
// Construct a Gregorian calendar for the current date and time
Calendar calendar =
new
GregorianCalendar();
6
7 System.out.println(
"Current time is "
+
new
Date());
8 System.out.println(
"YEAR: "
+ calendar.get(Calendar.YEAR));
9 System.out.println(
"MONTH: "
+ calendar.get(Calendar.MONTH));
10 System.out.println(
"DATE: "
+ calendar.get(Calendar.DATE));
11 System.out.println(
"HOUR: "
+ calendar.get(Calendar.HOUR));
12 System.out.println(
"HOUR_OF_DAY: "
+
13 calendar.get(Calendar.HOUR_OF_DAY));
14 System.out.println(
"MINUTE: "
+ calendar.get(Calendar.MINUTE));
15 System.out.println(
"SECOND: "
+ calendar.get(Calendar.SECOND));
16 System.out.println(
"DAY_OF_WEEK: "
+
17 calendar.get(Calendar.DAY_OF_WEEK));
18 System.out.println(
"DAY_OF_MONTH: "
+
19 calendar.get(Calendar.DAY_OF_MONTH));
20 System.out.println(
"DAY_OF_YEAR: "
+
21 calendar.get(Calendar.DAY_OF_YEAR));
22 System.out.println(
"WEEK_OF_MONTH: "
+
23 calendar.get(Calendar.WEEK_OF_MONTH));
24 System.out.println(
"WEEK_OF_YEAR: "
+
25 calendar.get(Calendar.WEEK_OF_YEAR));
26 System.out.println(
"AM_PM: "
+ calendar.get(Calendar.AM_PM));
27
28
calendar for current time
extract fields in calendar
// Construct a calendar for September 11, 2001
29
30 String[] dayNameOfWeek = {
"Sunday"
,
"Monday"
,
"Tuesday"
,
"Wednesday"
,
31
"Thursday"
,
"Friday"
,
"Saturday"
};
32 System.out.println(
"September 11, 2001 is a "
+
33 dayNameOfWeek[calendar1.get(Calendar.DAY_OF_WEEK) -
1
]);
34 }
35 }
Calendar calendar1 =
new
GregorianCalendar(
2001
,
8
,
11
);
create a calendar
Current time is Sun Nov 27 17:48:15 EST 2011
YEAR: 2011
MONTH: 10
DATE: 27
HOUR: 5
HOUR_OF_DAY: 17
MINUTE: 48
SECOND: 15
DAY_OF_WEEK: 1
DAY_OF_MONTH: 27
DAY_OF_YEAR: 331
WEEK_OF_MONTH: 5
WEEK_OF_YEAR: 49
AM_PM: 1
September 11, 2001 is a Tuesday
The
set(int field, value)
method defined in the
Calendar
class can be used to set a
field. For example, you can use
calendar.set(Calendar.DAY_OF_MONTH, 1)
to set the
calendar
to the first day of the month.
The
add(field, value)
method adds the specified amount to a given field. For exam-
ple,
add(Calendar.DAY_OF_MONTH, 5)
adds five days to the current time of the calen-
dar.
add(Calendar.DAY_OF_MONTH, -5)
subtracts five days from the current time of
the calendar.
set(field, value)
add(field, amount)