user1156041 user1156041 - 4 months ago 29
Android Question

Time incorrect after add format date in gson builder

I have json string which is returned from

mongodb
.

[{"_id":"578bb51aa51d15940688809e","name":"aaa","date":"2016-07-20T11:47:39.302Z"}]


I used
gson
to convert the Java Object. I got
Unparseable date: "2016-07-20T11:47:39.302Z"
. So I added date format to
gson
builder.

Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();


The date result is
Wed Jul 20 11:47:39 MMT 2016
. The time is
incorrect
.

What is the better date format pattern for date string?

How can I choose the suitable date format pattern by the given date string?

Answer

If I am not mistaken, you are having an issue with timezone information. Both the JavaScript Date object and the Java Date object represent a point in universal coordinated time (UTC). Neither the JavaScript Date object nor the Java Date object contain timezone information.


Side note: The Java Date object does actually contain timezone information, which is why you see the timezone (MMT in your case) when you call date.toString(). Though, this timezone should be ignored, as the timezone irregularities highlight some of the many issues with the Java 7- date/time classes.


The GsonBuilder().setDateFormat() method sets the string format that a Java Date object should be serialized to and deserialized from. This format does not contain any timezone information either because the Date object does not contain that information.

In order to display the UTC time your Date object represents in the correct timezone, you must provide that timezone. This is not done during deserialization with Gson, but when you actually display the date/time:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getDefault());

String zonedDateTime = simpleDateFormat.format(date);

Android also comes with a handy DateUtils class to use instead of SimpleDateFormat that will handle the timezone information for you, as well as Locale information.

DateUtils.formatDateTime(getContext(), date.getTime(),
                        DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_ABBREV_ALL);
Comments