Skip to content

java.util.Date is parsing wrong dates with dates before 1912

I don’t understand the reason why Jackson library is parsing wrong dates before 1912. I suppose the problem is the java.util.Date conversion, because the problem persists with Gson.

This is my code:

ObjectMapper mapper = new ObjectMapper();
String tmp = "{"date":"1911-01-01T00:00:00+00:00"}";
Response resp = mapper.readValue(tmp, Response.class);

date is a field of type java.util.Date

As you can see, the input is: 1911-01-01T00:00:00+00:00

And the output is: Sun Jan 01 00:09:21 CET 1911 (I don’t understand why that time is set)

But If I set this input: 1912-01-01T00:00:00+00:00

The ouput is correct: Mon Jan 01 00:00:00 CET 1912

Only happens with dates before 1912.

Jdk v1.8.0_101




Never use the legacy class Date. Do not waste your time trying to understand the awful mess that is Date and Calendar.

Use only the modern java.time classes. Later versions of Jackson support java.time.

OffsetDateTime odt = OffsetDateTime.parse( "1911-01-01T00:00:00+00:00" ) ;

When asked to produce text representing its value, that OffsetDateTime generates:

odt.toString(): 1911-01-01T00:00Z

The Z on the end means an offset of zero hours-minutes-seconds from UTC, and is pronounced “Zulu”.

For an explanation as to what happened with your code using the legacy classes, see the excellent Answer by Ole V.V. But notice that using the properly-designed classes in java.time avoids the underlying issue: Applying a time zone where none was called for.

A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Your input carries an offset (of zero), with no indication of time zone. So no need to involve a time zone in processing your input.