Calendar

V

Vova Reznik

Does anyone know why

Calendar c = Calendar.getInstance();
c.set(Calendar.AM_PM, Calendar.AM);
System.out.println(c.get(Calendar.AM_PM));

will always print 1 [PM]
 
R

Roedy Green

Calendar c = Calendar.getInstance();
c.set(Calendar.AM_PM, Calendar.AM);
System.out.println(c.get(Calendar.AM_PM));

c already contained a date and time timestamp. It already KNEW the
time was after noon. The AM_PM field would only be relevant if you
composed the field from bits and pieces including an hour.
 
P

P.Hill

Roedy said:
The AM_PM field would only be relevant if you
composed the field from bits and pieces including an hour.

Curiously enough that is the feature and it IS documented:

"Inconsistent information. If fields conflict, the calendar will give
preference to fields set more recently. For example, when determining
the day, the calendar will look for one of the following combinations of
fields. The most recent combination, as determined by the most recently
set single field, will be used.

[...]

For the time of day:

HOUR_OF_DAY
AM_PM + HOUR

"
see
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html

So in your case it didn't come up with AM_PM and the HOUR _combination_
as having been set, so it used the old HOUR_OF_DAY. The solution is to
change HOUR when you change AM_PM which could include getting the
existing value, thus the following code results in
the value you expected:

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, c.get(Calendar.HOUR));
c.set(Calendar.AM_PM, Calendar.AM);
System.out.println(c.get(Calendar.AM_PM));

-Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top