214

I'm trying to have a custom date format in Gson output, but .setDateFormat(DateFormat.FULL) doesn't seem to work and it the same with .registerTypeAdapter(Date.class, new DateSerializer()).

It's like Gson doesn't care about the object "Date" and print it in its way.

How can I change that?

Thanks

EDIT:

@Entity
public class AdviceSheet {
  public Date lastModif;
[...]
}

public void method {
   Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
   System.out.println(gson.toJson(adviceSheet);
}

I always use java.util.Date; setDateFormat() doesn't work :(

2
  • Have you checked that you are importing correct Date-class in all places? Also code example would be helpful.
    – M.L.
    Jul 29, 2011 at 14:24
  • What do you mean by doesn't work? What do you actually see? Jun 30, 2015 at 13:04

8 Answers 8

352

It seems that you need to define formats for both date and time part or use String-based formatting. For example:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

or using java.text.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

or do it with serializers:

I believe that formatters cannot produce timestamps, but this serializer/deserializer-pair seems to work

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();

If using Java 8 or above you should use the above serializers/deserializers like so:

JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
            : new JsonPrimitive(src.getTime());

JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());
3
  • Ok it works better with your way. But how can I display timestamps with this ? Aug 1, 2011 at 9:23
  • 6
    I am using Gson 2.2.4 and Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); works.
    – Ramsharan
    Aug 5, 2013 at 16:25
  • using Gson 2.2.2 and Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); works Nov 4, 2014 at 0:44
92
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

4
  • 1
    @Abhi - Why is quoting 'Z' necessary?
    – tj-recess
    Jan 30, 2015 at 1:55
  • 1
    I tried without quotes and gson threw Exception that the date is not parseable. Does it work for you without quotes?
    – Abhi
    Jan 30, 2015 at 11:43
  • 10
    ThIs is NOT right solution .. the Z means timezone and it represents UTC timezone, if you hardcode it like this you'll lost that info
    – Billda
    Apr 4, 2016 at 11:41
  • This is 8601 format which is right. The Z means UTC, but I am not sure how you set the time zone on the Gson object. That must be set as well or you will get the default time zone I would bet.
    – AgilePro
    Nov 9, 2022 at 4:57
6

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

5

In case if you hate Inner classes, by taking the advantage of functional interface you can write less code in Java 8 with a lambda expression.

JsonDeserializer<Date> dateJsonDeserializer = 
     (json, typeOfT, context) -> json == null ? null : new Date(json.getAsLong());
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,dateJsonDeserializer).create();
1
  • 1
    It seems that null check can be omitted (Gson does it itself): Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, (JsonDeserializer) (json, typeOfT, context) -> new Date(json.getAsLong())).create();
    – gmk57
    Sep 24, 2018 at 11:41
2

You can specify you format Gson gson = builder.setDateFormat("yyyy-MM-dd").create(); in this method instead of yyyy-MM-dd you can use anyother formats

 GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                                return new Date(json.getAsJsonPrimitive().getAsLong());
                            }
                        });

                        Gson gson = builder.setDateFormat("yyyy-MM-dd").create();
1

This is a bug. Currently you either have to set a timeStyle as well or use one of the alternatives described in the other answers.

0

I'm on Gson 2.8.6 and discovered this bug today.

My approach allows all our existing clients (mobile/web/etc) to continue functioning as they were, but adds some handling for those using 24h formats and allows millis too, for good measure.

Gson rawGson = new Gson();
SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss")
private class DateDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            return new rawGson.fromJson(json, Date.class);
        } catch (JsonSyntaxException e) {}
        String timeString = json.getAsString();
        log.warning("Standard date deserialization didn't work:" + timeString);
        try {
            return fmt.parse(timeString);
        } catch (ParseException e) {}
        log.warning("Parsing as json 24 didn't work:" + timeString);
        return new Date(json.getAsLong());
    }
}

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

I kept serialization the same as all clients understand the standard json date format.

Ordinarily, I don't think it's good practice to use try/catch blocks to govern flow control, but this should be a fairly rare case.

2
  • "I don't think it's good practice to use try/catch blocks" It is good practice to use them, it is bad if you want to control normal program flow with try/catch.
    – Kamil
    Dec 4, 2021 at 13:06
  • Kamil, that is what I meant. But upon rereading my answer, I agree with you that clarification is necessary Dec 5, 2021 at 18:31
0

This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO 8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.