Using Custom DateFormat

In this post, under GSON, I will explain how to use custom date format when serializing Java object containing date information to json format.

We can change this format globally, globally meaning the custom format will be applied to all objects that are serialized using Gson instance, created using the custom date format.

Below is an example

Main Code

1  import java.text.DateFormat;
2  import java.util.Date;
4  import;
5  import;
7  public class GsonDemo6 {
8   public static void main(String[] args) {
9       GsonBuilder gsonBuilder = new GsonBuilder();
10      Gson gson = gsonBuilder.setDateFormat(DateFormat.SHORT).create();
11      Student student = new Student();
12      student.setId(1);
13      student.setName("name1");
14      student.setRollnum(100);
15      student.setDate(new Date());
16      String result = gson.toJson(student);
17      System.out.println(result);
18  }
19 }

At line 9, we create a GsonBuilder instance which will help in creating an instance of Gson class.

At line 10, we set the date format by calling “setDateFormat” method and then will call “create” method. This will create a Gson instance with specified date format.

The argument to the “setDateFormat” method must be one of the predefined constants in the java.text.DateFormat class.

From line 11 to 15, we create a Student instance and set its properties.

At line 16, we serialize the student object to String in JSON format and print its result at line 17.

Below is the output


{“id”:1,”name”:”name1″,”rollnum”:100,”date”:”Aug 31, 2019 7:53:22 PM”}

Check these products on Amazon

Leave a Reply