java - DateFormat pattern "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" in Gson -
i have 2 field below (pay attending first field has milliseconds section):
{ "updatetime":"2011-11-02t02:50:12.208z", "delivertime":"1899-12-31t16:00:00z" }
i want deserialize json string object gson, gson
instance:
gsonbuilder gb = new gsonbuilder(); gb.setdateformat("yyyy-mm-dd't'hh:mm:ss.sss'z'"); gson = gb.create();
the first field deserialized java date type: 2011-11-02 02:50:12.208 (looks ignored time zone section-‘z’, that's expected). however, sec field deserialized 1900-01-01 00:00:00 (i live in china, +8 gmt here), seems time zone section-'z' plays part in deserialization.
why sec field uses time zone section? it's not expected.
quick answer
first string correctly parsed using date format , local time zone, sec 1 not respect it, parsed default simpledateformat
object has not milliseconds ("yyyy-mm-dd't'hh:mm:ss'z' parsing format) , uses utc timezone giving "shift" in time part.
full answer
to respond question need dive gson source code. more in particular have @ code of defaultdatetypeadapter
used parse dates. can find code @ link, quick reference re-create here relevant parts.
when phone call in builder:
gb.setdateformat("yyyy-mm-dd't'hh:mm:ss.sss'z'");
you initializing defaultdatetypeadapter in way:
defaultdatetypeadapter(dateformat enusformat, dateformat localformat) { this.enusformat = enusformat; this.localformat = localformat; this.iso8601format = new simpledateformat("yyyy-mm-dd't'hh:mm:ss'z'", locale.us); this.iso8601format.settimezone(timezone.gettimezone("utc")); }
where:
enusformat = new simpledateformat("yyyy-mm-dd't'hh:mm:ss.sss'z'")
, localformat = new simpledateformat("yyyy-mm-dd't'hh:mm:ss.sss'z'", locale.us)
since string have passed in builder.
pay attending locale.us
not timezone , iso8601format
same enusformat
without milliseconds utc timezone.
parsing happens deserializetodate
method:
private date deserializetodate(jsonelement json) { synchronized (localformat) { seek { homecoming localformat.parse(json.getasstring()); } grab (parseexception ignored) { } seek { homecoming enusformat.parse(json.getasstring()); } grab (parseexception ignored) { } seek { homecoming iso8601format.parse(json.getasstring()); } grab (parseexception e) { throw new jsonsyntaxexception(json.getasstring(), e); } } }
where of 3 date formats used in waterfall approach.
first json string: "2011-11-02t02:50:12.208z". it's parsed localformat
since has milliseconds , gives result expect using timezone.
second json string: "1899-12-31t16:00:00z". won't parsed localformat
since has not milliseconds, sec chance enusformat same pattern, except locale. fail @ same way.
last chance parse: iso8601format
, will, has no milliseconds, but, construction, utc time zone, parse date utc while others parsed using timezone.
java timezone gson
No comments:
Post a Comment