Skip to content

Gson – Date Format Java Example

Gson – Date format Java example shows how to format a date in the JSON using the Gson library in Java. This example also shows how to format a date in JSON using the GsonBuilder class.

How to format a date in JSON?

When we serialize an object to a JSON representation using the Gson library, any date fields that the object may have will have the date in the default format. Consider the below given example.

Output

As we can see from the output, the “dateOfJoining” field contains the date in the default format.

However, it is fairly easy to format the date field in JSON using the setDateFormat method of the Gson class.

This method sets the Gson object to serialize any Date objects in the format of the provided pattern. The pattern will be applied to any objects of the class Date and Timestamp.

The pattern needs to be as defined by the SimpleDateFormat class.

Here is an example that sets the date format to dd-mm-yyyy using the above method.

Output

We can also format the date to include hours, minutes, seconds, and even milliseconds as given below.

Output

The list of all supported formats can be found in this SimpleDateFormat class documentation.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.