Re: Date/Calendar confusion
John B. Matthews wrote:
Lew wrote:
John B. Matthews wrote:
Lew wrote:
John B. Matthews wrote:
Ulrich Scholz wrote:
[Valuable clarifications elided.]
calendar2.set(Calendar.YEAR, 1970);
calendar2.set(Calendar.MONTH, Calendar.JANUARY);
calendar2.set(Calendar.DAY_OF_MONTH, 1);
calendar2.clear(Calendar.HOUR);
Better: 'calendar2.set(Calendar.HOUR, 0);'
Can I impose on you to amplify further? Is this related to "the
resolution rule for the time of day," mentioned in clear(int)?
<http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#time_re=
solution>
<http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear(i=
nt)> >
I guess, but that's not my focus. My focus is on the fact that when
you 'clear(int)', as opposed to 'set(int,int)', the 'Calendar'
instance does no reconciliation, nor can you rely on any specific
field value such as '0'. 'clear()' sets fields to *undefined*, not a
specific value. It makes no attempt to reconcile field values, e.g.,
to set a day to a valid value based on the month value or vice versa.
So you have no promise as to what the values are after a 'clear()'.
What comes out might well surprise, as it did on that project some
years ago where I encountered this situation.
Hard fought, well remembered; thanks for elaborating.
Looking closer, I see that the resulting default value is reliable for
a particular concrete Calendar. For example, GregorianCalendar, Default=
Fields Values:
<http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.htm=
l>
A potential problem is that Calendar.getInstance(TimeZone zone,
Locale aLocale) may return an instance of a class with different
defaults.
'GregorianCalendar' was the concrete class that had problems in the
real-world system where I encountered the risks of 'clear()'.
It's not enough that the class returns default values for undefined
fields. 'clear()' does not invoke the reconciliation of different
fields with each other that lenient instances seek. So if you 'clear()'
some of the fields, you might end up with, say, a 'DAY_OF_WEEK' not
consistent with the 'DAY_OF_MONTH'.
I don't recall the exact details of the bug I saw, but it was along
those lines. It might have messed up a Daylight Saving calculation,
or maybe it was the consistency between fields - it's been about six
years and I don't remember. I do distinctly remember the "Eureka" that
the problem was the use of 'clear()' instead of 'set(field, 0)'.
--
Lew