user1156041 user1156041 - 1 year ago 199
Android Question

Time incorrect after add format date in gson builder

I have json string which is returned from



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

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

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 Source

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");

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download