GsonBuilder setDateFormat for "2011-10-26T20:29:59-07:00"

LuxuryMode picture LuxuryMode · Oct 27, 2011 · Viewed 42k times · Source

I'm getting a date/time in json as 2011-10-26T20:29:59-07:00. What's the proper way to use gsonBuilder.setDateFormat to properly format this time?

Answer

BalusC picture BalusC · Oct 27, 2011

The -07:00 is the ISO 8601 time zone notation. This is not supported by SimpleDateFormat until Java 7. So, if you can upgrade to Java 7, then you can use the X to represent that time zone notation:

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

On Java 6 you would need to do some pattern matching and replacing on the JSON string first to replace the -07:00 part by the RFC 822 notation -0700 so that you can use Z:

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

or by the general time zone notation GMT-07:00 so that you can use z:

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