Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

gson

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?

like image 667
LuxuryMode Avatar asked Oct 27 '11 01:10

LuxuryMode


1 Answers

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(); 
like image 102
BalusC Avatar answered Sep 21 '22 00:09

BalusC