Marky0 Marky0 - 1 year ago 351
JSON Question

Java Date to UTC using gson

I can't seem to get gson to convert a Date to UTC time in java....
Here is my code...

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
//This is the format I want, which according to the ISO8601 standard - Z specifies UTC - 'Zulu' time

Date now=new Date();

Here is my Output

Thu Sep 25 18:21:42 BST 2014 // Time now - in British Summer Time
-60 // As expected : offset is 1hour from UTC
"2014-09-25T18:21:42.026Z" // Uhhhh this is not UTC ??? Its still BST !!

The gson result I want and what I was expecting


I can clearly just subtract 1hr before the call toJson but this seems to be a hack. How can I configure gson to always convert to UTC ?

Answer Source

After some further research, it appears this is a known issue. The gson default serializer always defaults to your local timezone, and doesn't allow you to specify the timezone. See the following link.....

The solution is to create a custom gson type adaptor as demonstrated in the link:

public static class GsonUTCDateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {

    private final DateFormat dateFormat;

    public GsonUTCDateAdapter() {
      dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);      //This is the format I need
      dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                               //This is the key line which converts the date to UTC which cannot be accessed with the default serializer

    @Override public synchronized JsonElement serialize(Date date,Type type,JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(dateFormat.format(date));

    @Override public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
      try {
        return dateFormat.parse(jsonElement.getAsString());
      } catch (ParseException e) {
        throw new JsonParseException(e);

Then register it as follows :

  Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
  Date now=new Date();

This now correctly outputs the Date in UTC


Thanks go to the link author.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download