Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

json - 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);
System.out.println("Date->"+resp.date);

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

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

java.time

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...