How can we format a date using the Jackson library in Java?


A Jackson is a Java based library and it can be useful to convert Java objects to JSON and JSON to Java Object. A Jackson API is faster than other API, needs less memory area and is good for the large objects. We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.

Syntax

public ObjectMapper setDateFormat(DateFormat dateFormat)

Example

import java.io.*;
import java.text.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;

public class JacksonDateformatTest {
   final static ObjectMapper mapper = new ObjectMapper();
   public static void main(String[] args) throws Exception {
      JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
      mapper.setDateFormat(df);
      jacksonDateformat.dateformat();
}
   public void dateformat() throws Exception {
      String json = "{\"birthDate\":\"1980-12-08\"}";
      Reader reader = new StringReader(json);
      Employee emp = mapper.readValue(reader, Employee.class);
      System.out.println(emp);
   }
}

// Employee class
class Employee implements Serializable {
   private Date birthDate;
   public Date getBirthDate() {
      return birthDate;
   }
   public void setBirthDate(Date birthDate) {
      this.birthDate = birthDate;
   }
   @Override
   public String toString() {
      return "Employee [birthDate=" + birthDate + "]";
   }
}

Output

Employee [birthDate=Mon Dec 08 00:00:00 IST 1980]

Updated on: 06-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements