Skip to content
Advertisement

GSON – Date format

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:

JavaScript

I always use java.util.Date; setDateFormat() doesn’t work 🙁

Advertisement

Answer

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

JavaScript

or using java.text.DateFormat

JavaScript

or do it with serializers:

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement