Java 8
LocalDate
Jackson
JSON formatting
Date serialization

Java 8 LocalDate Jackson format

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java 8 introduced a new date and time API, which is part of the java.time package. One of the key classes introduced is LocalDate, which represents a date without time-zone in the ISO-8601 calendar system, such as 2000-01-01. Working with LocalDate can be straightforward, but when it comes to serializing and deserializing this class to and from JSON, you need to configure Jackson, the popular JSON library in Java, appropriately. This article explores details about Java 8 LocalDate and how it can be formatted using Jackson.

Introduction to LocalDate

LocalDate is immutable and thread-safe, representing a significant upgrade over the outdated java.util.Date class. It is often used when only a date is needed without any time or time-zone context.

Example Usage

java
1import java.time.LocalDate;
2
3public class LocalDateExample {
4    public static void main(String[] args) {
5        LocalDate today = LocalDate.now();
6        System.out.println("Today's Date: " + today);
7        
8        LocalDate specificDate = LocalDate.of(2020, 1, 1);
9        System.out.println("Specific Date: " + specificDate);
10    }
11}

Output:

 
Today's Date: 2023-10-05 (depending on the current date)
Specific Date: 2020-01-01

Jackson Integration

Jackson provides excellent support for Java 8 date and time API, but additional configuration is necessary because this support is not included by default. The jackson-datatype-jsr310 module must be added to your project, enabling Jackson to handle the new date/time types.

Maven Dependency

If you are using Maven, you need to add the following dependency to your pom.xml:

xml
1<dependency>
2    <groupId>com.fasterxml.jackson.datatype</groupId>
3    <artifactId>jackson-datatype-jsr310</artifactId>
4    <version>2.13.2</version>
5</dependency>

Configuring ObjectMapper

To handle LocalDate serialization and deserialization, you need to register the module with Jackson's ObjectMapper:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
3
4public class JacksonLocalDateExample {
5    public static void main(String[] args) throws Exception {
6        ObjectMapper mapper = new ObjectMapper();
7        mapper.registerModule(new JavaTimeModule());
8        
9        LocalDate date = LocalDate.of(2020, 1, 1);
10        String json = mapper.writeValueAsString(date);
11        System.out.println("Serialized LocalDate: " + json);
12        
13        LocalDate deserializedDate = mapper.readValue(json, LocalDate.class);
14        System.out.println("Deserialized LocalDate: " + deserializedDate);
15    }
16}

Handling Custom Formats

By default, Jackson will serialize LocalDate in the "yyyy-MM-dd" format. If a different format is needed, you can configure a DateTimeFormatter and use the @JsonFormat annotation or configure the ObjectMapper directly.

For example, using @JsonFormat:

java
1import com.fasterxml.jackson.annotation.JsonFormat;
2import java.time.LocalDate;
3
4public class Event {
5    @JsonFormat(pattern = "dd/MM/yyyy")
6    private LocalDate date;
7
8    // Getters and Setters
9}

Global Custom Format

Alternatively, setting the custom pattern globally in the ObjectMapper:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
3import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
4import java.time.format.DateTimeFormatter;
5
6public class CustomDateFormatExample {
7    public static void main(String[] args) throws Exception {
8        ObjectMapper mapper = new ObjectMapper();
9        JavaTimeModule module = new JavaTimeModule();
10        module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
11        mapper.registerModule(module);
12        
13        LocalDate date = LocalDate.of(2020, 1, 1);
14        String json = mapper.writeValueAsString(date);
15        System.out.println("Serialized with custom format: " + json);
16    }
17}

Summary Table

Below is a summary of key points regarding Java 8 LocalDate with Jackson:

FeatureDetails
Default Pattern"yyyy-MM-dd"
Module Requiredjackson-datatype-jsr310
Maven Dependencycom.fasterxml.jackson.datatype jackson-datatype-jsr310
Custom Pattern via @JsonFormatAnnotate the field or getter with @JsonFormat(pattern = "dd/MM/yyyy")
Custom Global PatternRegister custom LocalDateSerializer to JavaTimeModule
Thread-SafetyLocalDate is immutable and thread-safe

Conclusion

Incorporating LocalDate into your Java applications provides a more robust and straightforward way to handle date values, especially when leveraging Jackson for JSON processing. By setting up the appropriate modules and configurations, you can ensure seamless serialization and deserialization of your date objects, enabling flexible format management as needed.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.