How to format a date using the Gson library in Java?

A Gson is a JSON library for Java, which is created by Google. By using Gson, we can generate JSON and convert JSON to java objects. We can create a Gson instance by creating a GsonBuilder instance and calling with the create() method. The GsonBuilder().setDateFormat() method configures Gson to serialize Date objects according to the pattern provided.


public GsonBuilder setDateFormat(java.lang.String pattern)


import java.util.Date;
public class DateformatTest {
   public static void main(String[] args) {
      Employee emp = new Employee(115, "Surya", new Date(), 25000.00);
      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
      String result = gson.toJson(emp);
// Employee class
class Employee {
   private int id;
   private String name;
   private Date doj;
   private double salary;
   public Employee(int id, String name, Date doj, double salary) { = id; = name;
      this.doj = doj;
      this.salary = salary;



Updated on: 04-Jul-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started