Date/Calendar confusion

U

Ulrich Scholz

Dear all,

have a look at the function below (Java 5). The first result is 0 as expected. But why is the second one different?

Thanks, Ulrich


private static void testDate() throws ParseException
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setRawOffset(0); // get GMT time zone for sure
dateFormat.setTimeZone(timeZone);

Calendar calendar1 = Calendar.getInstance(timeZone, Locale.US);
Date date1 = dateFormat.parse("1970-01-01T00:00:00.000");
calendar1.setTime(date1);
System.out.println(calendar1.getTimeInMillis()); // is 0

Calendar calendar2 = Calendar.getInstance(timeZone, Locale.US);
Date date2 = dateFormat.parse("0000-00-00T00:00:00.000");
calendar2.setTime(date2);

// adjust for the epoch 01.01.1970
//
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);

System.out.println(calendar2.getTimeInMillis()); // should be 0 but is -124335907200000
}
 
N

nogales

Try this:


package snippet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Snippet {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setRawOffset(0); // get GMT time zone for sure
dateFormat.setTimeZone(timeZone);

Calendar calendar1 = Calendar.getInstance(timeZone, Locale.US);
Date date1 = dateFormat.parse("1970-01-01T00:00:00.000");
System.out.println(date1);
calendar1.setTime(date1);
System.out.println(calendar1.getTimeInMillis()); // is 0
System.out.println(calendar1);

Calendar calendar2 = Calendar.getInstance(timeZone, Locale.US);
Date date2 = dateFormat.parse("0001-01-01T00:00:00.000");
System.out.println(date2);
calendar2.setTime(date2);

// adjust for the epoch 01.01.1970
//
calendar2.set(Calendar.YEAR, calendar2.get(Calendar.YEAR) + 1969);
calendar2.set(Calendar.MONTH, calendar2.get(Calendar.MONTH));
calendar2.set(Calendar.DAY_OF_MONTH, calendar2.get(Calendar.DAY_OF_MONTH));
System.out.println(calendar2);

System.out.println(calendar2.getTimeInMillis()); // should be 0 but is -124335907200000

}
}
 
L

Lew

Ulrich said:
have a look at the function below (Java 5). The first result is 0 as expected. But why is the second one different?

private static void testDate() throws ParseException
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

It's lenient by default.
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#isLenient()
"The default is lenient."

Check the docs when you have a question like this.
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setRawOffset(0); // get GMT time zone for sure
WTF?

dateFormat.setTimeZone(timeZone);

Calendar calendar1 = Calendar.getInstance(timeZone, Locale.US);
Date date1 = dateFormat.parse("1970-01-01T00:00:00.000");
calendar1.setTime(date1);
System.out.println(calendar1.getTimeInMillis()); // is 0

Calendar calendar2 = Calendar.getInstance(timeZone, Locale.US);
Date date2 = dateFormat.parse("0000-00-00T00:00:00.000");

What date is that, really?
calendar2.setTime(date2);
// adjust for the epoch 01.01.1970
calendar2.set(Calendar.YEAR, calendar2.get(Calendar.YEAR) + 1970);
calendar2.set(Calendar.MONTH, calendar2.get(Calendar.MONTH) + 1);

By this time, 'get(Calendar.MONTH)' is probably not what you think.
calendar2.set(Calendar.DAY_OF_MONTH, calendar2.get(Calendar.DAY_OF_MONTH) + 1);

" As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class."
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
System.out.println(calendar2.getTimeInMillis()); // should be 0 but is -124335907200000
}

When you set the 'Calendar' to the invalid date, it readjusted its internalvalues so those
'00' values were made into valid values.
 
J

John B. Matthews

Ulrich Scholz said:
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.

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();
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);
calendar2.clear(Calendar.MINUTE);
calendar2.clear(Calendar.SECOND);
calendar2.clear(Calendar.MILLISECOND);
System.out.println(calendar2.getTimeInMillis()); // 0
}
 
L

Lew

John said:
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);'
 
L

Lew

John said:
[Valuable clarifications elided.]
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_resolution>
<http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear(int)>

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.
 
J

John B. Matthews

Lew said:
John said:
Lew said:
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_resolution>
<http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear(int)> > >

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.html>

A potential problem is that Calendar.getInstance(TimeZone zone,
Locale aLocale) may return an instance of a class with different
defaults.
 
L

Lew

John said:
Lew said:
John said:
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)?
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.html>

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)'.
 

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

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top