Re: Date/Calendar confusion
John B. Matthews wrote:
Ulrich Scholz wrote:
calendar2.set(Calendar.YEAR, calendar2.get(Calendar.YEAR) + 1970);
calendar2.set(Calendar.MONTH, calendar2.get(Calendar.MONTH) + 1);
calendar2.set(Calendar.DAY_OF_MONTH,
calendar2.get(Calendar.DAY_OF_MONTH) + 1);
Note that Calendar.JANUARY is not 1. Use clear() to set some or all
fields to a known (undefined, !isSet()) state.
DANGER!
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear()
"Sets all the calendar field values and the time value (millisecond offset from
the Epoch) of this Calendar undefined."
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear(int)
"Sets the given calendar field value and the time value (millisecond offset from
the Epoch) of this Calendar undefined."
These set the fields to *undefined* - not zero-equivalents.
I have seen bugs in production caused by a programmer confusing 'clear()'
with 'set(field, 0)'.
public static void main(String[] args) {
TimeZone timeZone = TimeZone.getTimeZone("GMT");
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MMM-dd HH:mm:ss.SSS Z");
Calendar calendar1 = Calendar.getInstance(timeZone);
System.out.println(f.format(calendar1.getTime()));
calendar1.clear();
Dangerous. You need to do something to set that 'Calendar' instance
to a consistent state now.
System.out.println(calendar1.getTimeInMillis()); // 0
Calendar calendar2 = Calendar.getInstance(timeZone);
System.out.println(f.format(calendar2.getTime()));
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);'
calendar2.clear(Calendar.MINUTE);
calendar2.clear(Calendar.SECOND);
calendar2.clear(Calendar.MILLISECOND);
System.out.println(calendar2.getTimeInMillis()); // 0
}
--
Lew